0

我有一个要求,用户将被问到 1-5 的一系列问题,问题将循环出现,例如用户首先回答第一个问题,然后单击下一个问题旁边,他也可以转到上一个问题。当问题结束时,他将提交。

我正在尝试遍历包含多个 div 螺母的 div 我在 angular 2 中使用 view child 时遇到错误

虚拟数据

 <div #message>
           <div>
               Here
           </div>
           <div>
               Here again
           </div>
       </div>
    </div>


<div *ngFor = "let in of input">
    {{in}}
</div>


@ViewChild('message') input :ElementRef;

控制台日志

XCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/questioncomponent/question.component.html:14:5 caused by: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
    at new Error (native)
    at NgFor.ngOnChanges (http://localhost:3000/node_modules/@angular/common/bundles/common.umd.js:1646:31) [angular]
    at Wrapper_NgFor.ngDoCheck (/CommonModule/NgFor/wrapper.ngfactory.js:49:20) [angular]
    at DebugAppView.View_QuestionComponent0.detectChangesInternal (/AppModule/QuestionComponent/component.ngfactory.js:102:20) [angular]
    at DebugAppView.AppView.detectChanges 
4

1 回答 1

0

以下代码应该可以工作。For loops需要用数组喂食。但是,您应该重新考虑是否有更好的方法来解决您的问题,而不是使用ElementRef. 查看API

你的模板

<div #message>
    <div>
        Here
     </div>
     <div>
        Here again
     </div>
   </div>
</div>

在你的组件中

@ViewChild("message") message:any;

ngAfterViewInit() {
  for (let div of this.message.nativeElement.children) {
        console.log(div.textContent);
    }
}
于 2017-01-30T13:12:59.873 回答