0

I have requirement where the user will be asked a series of questions from 1-5 and the questions will come in a loop like first the user answers first question and then clicks next to the next question and he can also go to the previous question . and when question ends he will submit.

i am trying to loop through a div containing multiple div's nut i am getting a error using view child in angular 2

dummy data

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


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


@ViewChild('message') input :ElementRef;

Console log

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 

1 Answers1

0

The following code should work. For loops need to be fed with an array. However, you should reconsider if there aren't better ways to solve your problem rather than using ElementRef. See the API

Your template

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

And in your component

@ViewChild("message") message:any;

ngAfterViewInit() {
  for (let div of this.message.nativeElement.children) {
        console.log(div.textContent);
    }
}
Jan B.
  • 6,030
  • 5
  • 32
  • 53
  • but how do we iterate through the div this was dummy data i want to change add a hide class and show the next div when the user clicks on a button –  Jan 30 '17 at 13:15
  • like a questionnaire –  Jan 30 '17 at 13:15
  • The requirements you have are conveyed in the first chapters of each Angular2 tutorial. Basically all you need is some div elements with ngIf and two buttons that skip the questionnaire pages. You really should read upon the basic techniques of Angular2. – Jan B. Jan 30 '17 at 13:21
  • I can use ngIf , but what it there are 10 such div's and is there any other way using loops i want to try that –  Jan 30 '17 at 13:30
  • It is hard to say without seeing what you have got so far. – Jan B. Jan 30 '17 at 14:37