我目前正面临一个关于 mat-chip-list with 和 inputs 的奇怪问题。我有一个包含两个表单控件的表单组:联系人和姓名。
this.form = this.formBuilder.group({
name: ['', [Validators.required]],
contactIds: ['', [Validators.required]]
})
此表单的 View 如下所示:
<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 的普通输入元素时,当我删除输入字段的内容时错误会正确显示。
在这种情况下,标记如下所示:
<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 对该搜索不友好。
有人遇到过这个问题吗?如果您需要说明,请告诉我。
最佳答案
您应该在 <mat-chip-list>
中添加验证器并防止无效项目添加如下。
组件:
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>
关于输入未显示验证错误的 Angular Material 垫芯片列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49880051/