【问题标题】:Angular material mat-chip-list with input not showing validation error输入未显示验证错误的角材料垫片列表
【发布时间】:2018-09-27 12:51:08
【问题描述】:

我目前正面临一个带有和输入的 mat-chip-list 的奇怪问题。我有一个表单组,它有两个表单控件:联系人和姓名。

this.form = this.formBuilder.group({
    name: ['', [Validators.required]],
    contactIds: ['', [Validators.required]]
})

此表单的视图如下所示:

<mat-form-field #contactsChipList>
    <mat-chip-list>
        <mat-chip *ngFor="let contact of contacts" [removable]="removable" (remove)="removeChipListItem(contact)">
            {{ contact.name | titlecase }} {{ contact.surname | titlecase }}
        <mat-icon matChipRemove *ngIf="removable"></mat-icon>
        </mat-chip>
        <input [matChipInputFor]="contactsChipList" placeholder="Contacts" formControlName="contactIds" />
        <mat-error *ngIf="form.hasError('required', 'contactIds')">This field is required</mat-error>
    </mat-chip-list>
</mat-form-field>

问题:当我从输入字段中删除所有元素时,父表单 (formGroup) 被标记为无效,但 formGroup 的错误属性不包含任何值。所以错误永远不会出现。

其他尝试:但是当我使用具有 matInput 属性且没有 mat-chip-list 的普通输入元素时,当我删除输入字段的内容时,错误会正确显示。 p>

在这种情况下,标记如下所示:

<div class="form-group">
    <mat-form-field>
        <input matInput placeholder="Contacts" formControlName="contactIds" />
        <mat-error *ngIf="form.hasError('required', 'contactIds')">This field is required</mat-error>
    </mat-form-field>
</div>

假设:我现在认为问题出在 mat-chip-list 元素上。我试图调查: @Input()errorStateMatcher: ErrorStateMatcher 但我不确定如何使用。 Google 对该搜索并不友好。

有人遇到过这个问题吗?如果您需要澄清,请告诉我。

【问题讨论】:

    标签: angular typescript angular-material2


    【解决方案1】:

    您应该在&lt;mat-chip-list&gt;中添加验证器并防止添加无效项,如下所示。

    组件:

    export class ExampleComponent {
        items = [];
        emailFormControl = new FormControl('', [Validators.email]);
    
        addItem(event) {
            if (this.emailFormControl.valid) {
                items.push(event.value)
            }
        }
    
        .
        .
        .
    }
    

    模板:

    <mat-form-field>
        <mat-chip-list [formControl]="emailFormControl">
            .
            .
            .
        </mat-chip-list>
    </mat-form-field>
    

    已编辑: 看来您使用的是FormGroup。您必须将ngDefaultControl 添加到mat-chip-list,如下所示。你可以阅读一个很好的解释here

    <mat-form-field>
        <mat-chip-list ngDefaultControl [formControl]="form.controls.contactIds">
            .
            .
            .
            <mat-error *ngIf="form.controls.contactIds.hasError('required', 'contactIds')">This field is required</mat-error>
        </mat-chip-list>
    </mat-form-field>
    

    【讨论】:

      猜你喜欢
      • 2019-05-27
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多