【问题标题】:Angular Material Mat-Chip validation in template driven form模板驱动形式的 Angular Material Mat-Chip 验证
【发布时间】:2018-12-23 13:23:55
【问题描述】:

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

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

【问题讨论】:

  • 为什么不使用 ng-chips? git repo:github.com/Gbuomprisco/ngx-chips demo:angular-mfppay.stackblitz.io 它将项目存储在一个数组中,因此您可以轻松地使用数组长度验证保存按钮。有意义吗?
  • 感谢您的建议。我稍后会尝试 ngx-chips。
  • 您是否在混合使用模板驱动表单和响应式表单?这似乎是原因 - 您的“水果”未显示在表单中 - 您可以通过在模板中显示 {{ sampleForm.form .value | json }} 来尝试。

标签: angular angular-material angular6 angular-validation angular-material-6


【解决方案1】:

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

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

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

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

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

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

【讨论】:

    【解决方案2】:

    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>
    

    【讨论】:

    • 在您发布答案之前,我已经通过另一个答案解决了这个问题。这是相同的答案。谢谢
    猜你喜欢
    • 2018-10-02
    • 2019-04-28
    • 2022-11-10
    • 2023-02-25
    • 2017-08-05
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    相关资源
    最近更新 更多