我目前面临着一个带有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>
Problem: 当我从输入字段中删除所有元素时,父窗体(formGroup)被标记为无效,但formGroup的error属性不包含任何值 . 所以错误从未显示出来 .
Other attempt: 但是当我使用带有matInput属性的普通输入元素而没有mat-chip-list时,当我删除输入字段的内容时,错误会正确显示 .
这是标记在这种情况下的样子:
<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>
Assumption: 我现在认为问题在于mat-chip-list元素 . 我试着调查: @Input()errorStateMatcher: ErrorStateMatcher
但我不确定如何使用 . 谷歌对该搜索并不友好 .
有没有人遇到过这个问题?如果您需要澄清,请告诉我 .
1 回答
您应该在
<mat-chip-list>
中添加验证器并防止无效项添加,如下所示 .零件:
模板:
Editted: 好像你使用
FormGroup
. 您必须将ngDefaultControl
添加到mat-chip-list
,如下所示 . 你可以阅读一个很好的解释here .