问题
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