加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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元素.我试着调查一下:
?@Input()errorStateMatcher:ErrorStateMatcher
?但我不知道该如何使用.谷歌对该搜索并不友好.

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

解决方法

您应该在< 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:
您似乎使用FormGroup.您必须将ngDefaultControl添加到mat-chip-list,如下所示.你可以阅读一个很好的解释here.

<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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读