Glo*_*ire 7 typescript angular-material2 angular
我目前面临带有和输入的mat-chip-list的奇怪问题。我有一个包含两个表单控件的表单组:联系人和姓名。
this.form = this.formBuilder.group({
name: ['', [Validators.required]],
contactIds: ['', [Validators.required]]
})
Run Code Online (Sandbox Code Playgroud)
该表单的视图如下所示:
<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>
Run Code Online (Sandbox Code Playgroud)
问题:当我从输入字段中删除所有元素时,父表单(formGroup)被标记为无效,但是formGroup的error属性不包含任何值。因此错误永远不会显示。
其他尝试:但是,当我使用普通的具有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>
Run Code Online (Sandbox Code Playgroud)
假设:我现在认为问题出在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)
}
}
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
模板:
<mat-form-field>
<mat-chip-list [formControl]="emailFormControl">
.
.
.
</mat-chip-list>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)
编辑:
看来您使用FormGroup. 您必须添加ngDefaultControl到mat-chip-list以下内容。你可以在这里阅读一个很好的解释。
<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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8948 次 |
| 最近记录: |