Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ViewChild for dynamic elements - Angular 2 & ionic 2

I want to use multiple IonicSlides that I added dynamically. But I can't use @viewChild. please suggest a way to resolve this problem.

Template.html :

<div *ngFor="let name of title;let i = index;">
    <ion-slides  id="something" #slides>
        //some code
    </ion-slides>
</div

Component.ts :

  @ViewChild('slides') slides: QueryList<Slides>;

  ....

  ngAfterViewInit(){
        setTimeout(()=>{
              alert(this.slides.toArray()); //this line rise error 
        }, 3000);
  }

Error :

_this.slides.toArray is not a function

like image 824
Mohsen Avatar asked Feb 01 '18 12:02

Mohsen


People also ask

Can I use ViewChild in directive?

With @ViewChild, we can inject any component or directive (or HTML element) present on the template of a given component onto the component itself.

What is the difference between ViewChild and ViewChildren in angular?

ViewChildren is different from the ViewChild . ViewChild always returns the reference to a single element. If there are multiple elements the ViewChild returns the first matching element, ViewChildren always returns all the elements as a QueryList.

How does ViewChild work in angular?

ViewChildlinkProperty decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.


1 Answers

Use @ViewChildren instead of @ViewChild , Read More

@ViewChild :

You can use ViewChild to get the first element or the directive matching the selector from the view DOM.

@ViewChildren :

You can use ViewChildren to get the QueryList of elements or directives from the view DOM.

like image 162
Vivek Doshi Avatar answered Sep 17 '22 11:09

Vivek Doshi