如何使用ViewChildren使用模板变量来获取多个本机元素? [英] How can I use ViewChildren to get multiple native elements using template variables?
问题描述
我正在尝试使用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返回未定义.我认为ViewChildren通常与角度组件而不是本机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
,因为您问得太早了.在调用ngOnInit
之后且在ngAfterViewInit
之前填充ViewChildren
.
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屋!