Angular 14中Angular Material芯片列表报错原因及修复方案
Angular Material芯片字段报错问题解决
1. 报错原因
你的代码里存在冗余的嵌套结构:myForm中的businessLines是一个FormGroup,内部又包裹了同名的FormArray。但在businessLineControls getter中,你错误地将外层的FormGroup断言为FormArray,导致businessLineControls.value返回的是包含数组的对象而非直接的数组。*ngFor仅支持遍历数组这类可迭代对象,遍历对象就会触发该错误。
2. 可靠修复方式
步骤1:修正表单结构(TS代码)
移除冗余的外层FormGroup,直接将businessLines定义为FormArray:
constructor(private fb: FormBuilder,) { } public visible: boolean = true; public selectable: boolean = true; public removable: boolean = true; public addOnBlur: boolean = true; public readonly separatorKeysCodes: number[] = [ENTER, COMMA]; public myForm: FormGroup = new FormGroup({ companyName: new FormControl('', Validators.required), countryName: new FormControl('', Validators.required), // 直接定义为FormArray,无需外层FormGroup包裹 businessLines: this.fb.array([], Validators.required), }); // 修正getter,正确获取FormArray get businessLineControls(): FormArray { return this.myForm.get('businessLines') as FormArray; } public add(event: MatChipInputEvent): void { const input = event.input; const value = event.value; if ((value || "").trim()) { this.businessLineControls.push(this.fb.control(value.trim())); } if (input) { input.value = ""; } } // 改用索引删除,避免重复值导致的删除错误 public remove(index: number): void { if (index >= 0) { this.businessLineControls.removeAt(index); } }
步骤2:修正模板代码
调整formArrayName绑定,并优化*ngFor遍历逻辑:
<form [formGroup]="myForm" novalidate> <mat-form-field appearance="outline" floatLabel="always" class="example-chip-list"> <mat-label>Business lines:</mat-label> <!-- 直接绑定到businessLines这个FormArray --> <mat-chip-list #chipList aria-label="Delete business line" formArrayName="businessLines"> <!-- 遍历FormArray的controls,通过索引删除更可靠 --> <mat-chip *ngFor="let lineControl of businessLineControls.controls; let i = index" [selectable]="selectable" [removable]="removable" (removed)="remove(i)"> {{lineControl.value}} <mat-icon matChipRemove *ngIf="removable">Cancel</mat-icon> </mat-chip> <input placeholder="New business line..." [matChipInputFor]="chipList" [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur" (matChipInputTokenEnd)="add($event)"> </mat-chip-list> </mat-form-field> </form>
内容的提问来源于stack exchange,提问作者Razvan Zamfir
相关产品推荐
相关产品推荐

