Angular mat-select多选重置触发Error trying to diff错误如何解决
mat-select多选重置报错解决方案
错误原因
mat-select开启multiple多选模式时,绑定的ngModel值必须为数组类型。你在重置操作中:
- 将绑定选中值的
formData.student赋值为空字符串 - 将用于遍历生成选项的
studentList也赋值为空字符串
Angular做变化检测时需要对可迭代对象执行对比操作,无法处理字符串类型的输入,因此抛出Error: Error trying to diff ''. Only arrays and iterables are allowed错误。此外你的HTML代码中mat-option的属性绑定存在语法错误,也会导致功能异常。
修复步骤
1. 修正HTML绑定语法
删除错误的[selected]属性,修正[value]和属性引号规范:
<mat-form-field appearance="outline" fxFlex="100" > <mat-label>StudentList</mat-label> <mat-select multiple (selectionChange)="checkAllSelected(formData.student)" class="componentWidth" [(ngModel)]="formData.student" [ngModelOptions]="{standalone: true}" > <mat-option *ngFor="let student of studentList" [value]="student"> {{student.name}} </mat-option> </mat-select> </mat-form-field>
2. 修正reset方法赋值逻辑
多选绑定值重置为空数组,studentList如果不需要清空就不要修改,确实要清空也赋值为空数组:
resetAll() { this.formData.period = ""; this.formData.meetingCode = ""; this.formData.meetingName = ""; this.formData.chosenDate = ""; this.formData.academic = ""; // 多选选中值重置为空数组 this.formData.student = []; this.formData.time_from = ""; this.formData.time_to = ""; this.meetingType = ''; // 若不需要清空选项列表可注释此行,需要清空则赋值空数组而非空字符串 // this.studentList = []; }
额外注意
初始化formData时,student字段的初始值也要设置为[],避免首次加载时出现同类报错。
内容的提问来源于stack exchange,提问作者PeaceoutTECH
相关产品推荐
相关产品推荐

