Angular Material 模板驱动形式的 Mat-Chip 验证

Angular Material Mat-Chip validation in template driven form

我正在使用 Angular 6 和 Angular Material 6。我想要 mat-chip 字段。当我输入 mat-chip 字段时,保存按钮将启用,否则将被禁用。输入字段是必需的,但不能要求 mat-chip 字段。请帮助我找到解决方案。谢谢

我的示例代码 link 在这里:stackblitz demo

在您的保存按钮中,您可以使用已禁用的 属性,但应该是这样的:

[disabled]="company_name === undefined || fruits.length === 0"

其他前来回答这个问题的人:

您可以使用另一个很棒的软件包,它可以为您的标签提供验证,它的名称是 ng-chips

Git 回购: github.com/Gbuomprisco/ngx-chips

在线演示:angular-mfppay.stackblitz.io

Solution

HTML:

<form #sampleForm="ngForm">

    <mat-form-field class="example-chip-list">
        <input matInput placeholder="Company Name" required="true" name="company_name" [(ngModel)]="company_name">
    </mat-form-field>

    <mat-form-field class="example-chip-list">
        <mat-chip-list #chipList>
            <mat-chip *ngFor="let fruit of fruits" [selectable]="selectable" [removable]="removable" (removed)="remove(fruit)">
                {{fruit}}
                <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
            </mat-chip>
            <input placeholder="New fruit..." #fruitInput [formControl]="fruitCtrl" [matAutocomplete]="auto" [matChipInputFor]="chipList"
             [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur" (matChipInputTokenEnd)="add($event)">
        </mat-chip-list>
        <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
            <mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
                {{fruit}}
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>


    <button fxFlex="30" mat-raised-button color="primary" [disabled]="!sampleForm.form.valid || company_name === undefined || fruits.length === 0">Save</button>
</form>