【问题标题】:Use ViewChild for dynamic elements - Angular 2 & ionic 2将 ViewChild 用于动态元素 - Angular 2 和 ionic 2
【发布时间】:2018-07-11 18:03:09
【问题描述】:

我想使用我动态添加的多个IonicSlides。但我不能使用@viewChild。请提出解决此问题的方法。

模板.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);
  }

错误:

_this.slides.toArray 不是函数

【问题讨论】:

  • 请不要使用警报进行调试,现在是 2020 年
  • @refaelio 问题是 2 年前的问题,不是 2020 年。哈哈
  • @Mohsen 2018 年和 2020 年一样糟糕,只是听起来没有那么酷,哈哈
  • @Mohsen 这只是一个比喻

标签: javascript angular ionic2 viewchild


【解决方案1】:

使用@ViewChildren 代替@ViewChildRead More

@ViewChild

您可以使用 ViewChild 来获取第一个元素或指令 匹配视图 DOM 中的选择器。

@ViewChildren

您可以使用 ViewChildren 获取元素的 QueryList 或 来自视图 DOM 的指令。

【讨论】:

    【解决方案2】:

    @ViewChild 用于单个元素或指令。要从视图 DOM 中获取元素或指令的 QueryList,请使用 @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));
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-30
      • 2019-01-20
      • 2016-06-21
      • 2017-03-11
      • 2017-03-22
      • 2018-08-07
      • 2018-02-21
      • 2018-12-16
      • 2017-12-14
      相关资源
      最近更新 更多