【发布时间】:2019-09-12 05:03:34
【问题描述】:
我有一个'mat-form-field' 输入,我在其上显示代表不同服装尺寸的mat-chip 元素列表。筹码可以是'L'、'S'等...
目前,这就是我遍历所有尺寸列表并显示它们的方式:
`
<mat-chip-list formArrayName="sizes" #chipList [multiple]="true" [selectable]="true">
<mat-chip #chipRef
*ngFor="let gearSize of gearItemForm.controls['sizes'].value; let i=index"
[selected]="gearSize.size.available"
(click)="gearSize.size.available = !gearSize.size.available; onSelectedChipSize()"
[color]="gearSize.size.color">{{ sizeEnum[gearSize.size.size] }}
</mat-chip>
</mat-chip-list>
<input
matInput
[formGroupName]="0"
placeholder="Gear sizes..."
[matChipInputFor]="chipList"
style="display: none;"
class="gear-size-label"
>
<span>Is form array sizes invalid: {{gearItemForm.get('sizes').touched}}</span>
<mat-error *ngIf="gearItemForm.get('sizes').invalid && gearItemForm.get('sizes').touched">Please select a size</mat-error>
</mat-form-field>
`
这就是我设置表单的方式:
`
this.gearItemForm = this.fb.group({
name: this.fb.control(name, Validators.required),
price: this.fb.control(price, Validators.required),
sizes: this.fb.array(sizesForm, this.requireSize()),
inStock: this.fb.control(inStock)
})
`
sizesForm 在哪里:
`
for (let index = 0; index < this.gearSizes.length; index++) {
sizesForm.push(this.fb.group({
'size': this.fb.control(sizes[index])
}))
}
`
我的问题是我有一个自定义验证器,它要求用户在将新商品发布到商店之前选择商品的尺寸。一切都按预期工作,但如果用户没有选择任何尺寸,我会尝试显示错误消息。目前一切正常,因为如果表单无效,我会禁用表单“提交”按钮。如果我没有选择任何筹码,则表格的“提交”按钮将被禁用。但是,我无法使用 'mat-error' 让表单显示任何错误,即使 <mat-error *ngIf="gearItemForm.get('sizes').invalid">Please select a size</mat-error> 返回 true 表示其无效。
【问题讨论】: