仅在创建元素后才使用 @ViewChild 获取 html 元素

Pic*_*cci 2 rxjs angular

我有一个 Angular 组件,其模板中有一个 html 元素。我希望能够在某个 Observable 发出任何值时创建该元素。因此我对元素进行了这样的编码

<div #myDiv *ngIf="myObs | async"> this is my div </div>
Run Code Online (Sandbox Code Playgroud)

myObs可观察到的在哪里。

同时我想以编程方式管理这个元素,因此我ViewChild像这样使用

@ViewChild('myDiv') myDiv: ElementRef;
....
ngAfterViewInit() {
  const myNativeElement = this.myDiv.nativeElement;
  doStuffWith(myNativeElement);
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,ngAfterViewInit运行时this.myDiv为 null,并且仅在myObs发出后才创建。

doStuffWith(myNativeElement)我想知道哪种方法是确保仅在this.myDiv实际创建时执行的最佳方法。

这是重现该案例的示例代码

jo_*_*_va 5

我会在以下位置使用设置器@ViewChild

@ViewChild('myDiv') set myDiv(myDiv: ElementRef) {
    doStuffWith(myDiv.nativeElement);
}
Run Code Online (Sandbox Code Playgroud)

*ngIf一旦成为,设置器将被调用true

您还可以通过使用私有属性并在 setter 中设置它来保留对元素的引用。