Angular中ngFor绑定数组渲染下拉框时出现迭代对象错误求助
解决Angular NgFor报错:Cannot find a differ supporting object '[object Object]'
这个错误的根源其实很直白——你在模板里重复使用了同一个变量名!
看你的HTML代码:你给<mat-select>加了模板引用变量 #subLandscape="ngModel",但这个名字和组件类里定义的数组public subLandscape: string[] = ['DEV', 'Testing', 'QA', 'UAT']完全重名了。在Angular模板的作用域里,模板引用变量的优先级比组件类的属性更高,所以当*ngFor="let item of subLandscape"执行时,它遍历的不是你定义的数组,而是ngModel的实例(一个对象),这就导致了NgFor无法处理非可迭代对象的错误。
修复方案:修改模板引用变量的名字
把模板里的#subLandscape="ngModel"改成其他不冲突的名字,比如#subLandscapeCtrl="ngModel",然后把所有用到ngModel状态校验的地方都替换成这个新名字。
修改后的HTML代码:
<div class="form-group" [class.has-error]="subLandscapeCtrl.invalid && subLandscapeCtrl.touched"> <strong>Sub Landscape</strong> <br> <p>Please choose from one of the Sub Landscape options. Sub Landscape options are for reporting only.</p> <label class="control-label">SubLandscape:</label> <mat-select #subLandscapeCtrl="ngModel" type="text" class="form-control" name="subLandscape" [ngModel]="model.subLandscape"> <mat-option *ngFor="let item of subLandscape"> {{ item }} </mat-option> </mat-select> <div *ngIf="subLandscapeCtrl.invalid && subLandscapeCtrl.touched" class="alert alert-danger"> Select the Sub Landscape from the provided list. </div> </div>
这样修改后,*ngFor就能正确引用组件类里的subLandscape数组了,而ngModel的状态检查也会使用新的模板引用变量subLandscapeCtrl,错误自然就消失了。
你的Component和Model代码不需要做任何修改,保持原样即可。
内容的提问来源于stack exchange,提问作者MANOJ
相关产品推荐
相关产品推荐

