gpt4 book ai didi

angular - *ngIf 中的@ViewChild

转载 作者:太空狗 更新时间:2023-10-29 16:44:24 33 4
gpt4 key购买 nike

问题

在显示模板中的相应元素后,获取 @ViewChild 的最优雅方法是什么?

下面是一个例子。还有 Plunker可用。

Component.template.html:

<div id="layout" *ngIf="display">
<div #contentPlaceholder></div>
</div>

组件.component.ts:

export class AppComponent {

display = false;
@ViewChild('contentPlaceholder', { read: ViewContainerRef }) viewContainerRef;

show() {
this.display = true;
console.log(this.viewContainerRef); // undefined
setTimeout(() => {
console.log(this.viewContainerRef); // OK
}, 1);
}
}

我有一个组件,其内容默认隐藏。当有人调用 show() 方法时,它就会变得可见。但是,在 Angular 2 更改检测完成之前,我无法引用 viewContainerRef。我通常将所有必需的操作包装到 setTimeout(()=>{},1) 中,如上所示。有没有更正确的方法?

我知道 ngAfterViewChecked 有一个选项,但它会导致太多无用的调用。

ANSWER (Plunker)

最佳答案

为 ViewChild 使用 setter:

 private contentPlaceholder: ElementRef;

@ViewChild('contentPlaceholder') set content(content: ElementRef) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}

一旦 *ngIf 变为 true,就会使用元素引用调用 setter。

请注意,对于 Angular 8,您必须确保设置 { static: false },这是其他 Angular 版本中的默认设置:

 @ViewChild('contentPlaceholder', { static: false })

注意:如果 contentPlaceholder 是一个组件,您可以将 ElementRef 更改为您的组件类:

  private contentPlaceholder: MyCustomComponent;

@ViewChild('contentPlaceholder') set content(content: MyCustomComponent) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}

关于angular - *ngIf 中的@ViewChild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39366981/

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