如何使用 ViewChildren 使用模板变量获取多个原生元素?

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

我正在尝试使用 ViewChildren 从我的模板中获取堆叠 canvas 元素的数组,这样我以后就可以像在绘图程序中的图层一样在它们上进行绘制。

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

当我这样做时,ViewChildren returns 未定义。我认为 ViewChildren 通常与 angular 组件一起使用,而不是原生 HTML 元素,但我宁愿不创建一个新组件只是为了封装 canvas。

返回 undefined 因为你问得太早了。 ViewChildren 在调用 ngOnInit 之后和 ngAfterViewInit.

之前填充
  ngAfterViewInit () {
     // this.canvasLayers works here
  }

查看 docs on lifecycle hooks