如何使用 ViewChildren 使用模板变量获取多个本机元素? [英] How can I use ViewChildren to get multiple native elements using template variables?

查看:22
本文介绍了如何使用 ViewChildren 使用模板变量获取多个本机元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ViewChildren 从我的模板中获取一组堆叠的画布元素,以便我以后可以像绘图程序中的图层一样在它们上绘图.

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.

<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
  }
}

当我这样做时,ViewChildren 返回 undefined.我认为 ViewChildren 通常与 angular 组件一起使用,而不是原生 HTML 元素,但我宁愿不创建一个新组件来封装画布.

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.

推荐答案

它返回 undefined 因为你问得太早了.ViewChildrenngOnInit 调用之后和 ngAfterViewInit 之前填充.

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
  }

查看关于生命周期挂钩的文档.

这篇关于如何使用 ViewChildren 使用模板变量获取多个本机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆