输入未显示验证错误的 Angular Material 垫芯片列表

标签 angular typescript angular-material2

我目前正面临一个关于 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 .您必须添加 ngDefaultControlmat-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/

相关文章:

angular - Angular Material 数据表中的内联编辑

typescript - Angular 2 RC2 单选按钮绑定(bind)损坏

javascript - Nestjs路由器中的 Controller 如何拆分路由

angular - 如何在 Angular 4 中禁用 md-select 的键盘交互?

angular - 如何使用 Angular 在 vi​​s.js 中实现网络可视化?

javascript - splice 在从数组中删除条目时创建 NULL 条目

html - 垫扩展面板删除边框

javascript - 如何使用 $q 返回一个 http 请求异步的值(使用 typescript)

javascript - 网站无法在某些 IOS 设备上呈现 [白屏死机?]

angular - 找不到 Angular Material 核心主题