Angular材料mat-chip-list,输入未显示验证错误
发布时间:2020-12-17 17:11:18 所属栏目:安全 来源:网络整理
导读:我目前正面临着一个带有mat-chip-list和输入的奇怪问题.我有一个表单组,有两个表单控件:联系人和名称. this.form = this.formBuilder.group({ name: ['',[Validators.required]],contactIds: ['',[Validators.required]]}) 此表单的视图如下所示: mat-form
我目前正面临着一个带有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的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> 假设:我现在认为问题在于mat-chip-list元素.我试着调查一下: 有没有人遇到过这个问题?如果您需要澄清,请告诉我. 解决方法
您应该在< mat-chip-list>中添加验证器.并防止无效项目添加如下.
零件: export class ExampleComponent { items = []; emailFormControl = new FormControl('',[Validators.email]); matcher = new ErrorStateMatcher(); addItem(event) { if (this.emailFormControl.valid) { items.push(event.value) } } . . . } 模板: <mat-form-field> <mat-chip-list [errorStateMatcher]="matcher" [formControl]="emailFormControl"> . . . </mat-chip-list> </mat-form-field> Editted: <mat-form-field> <mat-chip-list ngDefaultControl [errorStateMatcher]="matcher" [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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |