简体   繁体   中英

Use ViewChild for dynamic elements - Angular 2 & ionic 2

I want use multiple IonicSlides that I added thease dynamically, So I can't use viewChild . please suggest a way for 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

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.

@ViewChild is for for single element or directive. To get get the QueryList of elements or directives from the view DOM, use @ViewChildren

HTML

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

Component.ts

@ViewChildren("slides") private slides: QueryList<ElementRef>;
  ....

ngAfterViewInit(): void {
    this.slides.changes.subscribe(() => console.log(this.slides));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM