gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:22:18 24 4
gpt4 key购买 nike

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

<div #myDiv *ngIf="myObs | async"> this is my div </div>

其中 myObs 是 Observable。

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

@ViewChild('myDiv') myDiv: ElementRef;
....
ngAfterViewInit() {
const myNativeElement = this.myDiv.nativeElement;
doStuffWith(myNativeElement);
}

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

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

This is a sample code to reproduce the case .

最佳答案

我会在@ViewChild上使用setter:

@ViewChild('myDiv') set myDiv(myDiv: ElementRef) {
doStuffWith(myDiv.nativeElement);
}

一旦*ngIf变为true,setter就会被调用。

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

关于angular - 仅在创建元素后才使用 @ViewChild 获取 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54430759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com