How can I use ViewChildren to get multiple native elements using template variables?

冷暖自知 提交于 2019-12-13 00:25:05

问题


I'm trying to use ViewChildren to get an Array of stacked canvas elements from my template so I can later draw on them like layers in a drawing program.

drawing.component.html

<canvas #canvaslayer style="z-index: 0;"></canvas>
<canvas #canvaslayer style="z-index: 1;"></canvas>
<canvas #canvaslayer style="z-index: 2;"></canvas>

drawing.component.ts

@Component({
  selector: 'app-drawing',
  templateUrl: './drawing.component.html',
})

export class DrawingComponent implements OnInit {


  @ViewChildren('canvaslayer') canvasLayers: QueryList<ElementRef>;

  ngOnInit() {
     //this.canvasLayers == undefined here and
     //this.canvasLayers[0].nativeElement throws an exception
  }
}

When I do this, ViewChildren returns undefined. I think ViewChildren is typically used with angular components instead of native HTML elements, but I would rather not create a new component just to encapsulate canvas.


回答1:


It returnes undefined because you're asking too early. The ViewChildren are populated after ngOnInit is called and before ngAfterViewInit.

  ngAfterViewInit () {
     // this.canvasLayers works here
  }

Check out docs on lifecycle hooks.



来源:https://stackoverflow.com/questions/53543714/how-can-i-use-viewchildren-to-get-multiple-native-elements-using-template-variab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!