* ngIf中的@ViewChild [英] @ViewChild in *ngIf
问题描述
在显示模板中的相应元素之后,最优雅的获取@ViewChild
的方法是什么?
What is the most elegant way to get @ViewChild
after corresponding element in template was shown?
下面是一个示例.还可以柱塞.
Below is an example. Also Plunker available.
模板:
<div id="layout" *ngIf="display">
<div #contentPlaceholder></div>
</div>
组件:
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)
中,如上所示.有没有更正确的方法?
I have a component with its contents hidden by default. When someone calls show()
method it becomes visible. However, before Angular 2 change detection completes, I can not reference to viewContainerRef
. I usually wrap all required actions into setTimeout(()=>{},1)
as shown above. Is there a more correct way?
我知道ngAfterViewChecked
有一个选项,但是它会导致太多无用的调用.
I know there is an option with ngAfterViewChecked
, but it causes too much useless calls.
推荐答案
为ViewChild使用设置器:
Use a setter for the ViewChild:
private contentPlaceholder: ElementRef;
@ViewChild('contentPlaceholder') set content(content: ElementRef) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}
一旦*ngIf
变为true
,将使用元素引用来调用setter.
The setter is called with an element reference once *ngIf
becomes true
.
注意,对于Angular 8,您必须确保设置{ static: false }
,这是其他Angular版本中的默认设置:
Note, for Angular 8 you have to make sure to set { static: false }
, which is a default setting in other Angular versions:
@ViewChild('contentPlaceholder', { static: false })
注意:如果contentPlaceholder是组件,则可以将ElementRef更改为组件类:
Note: if contentPlaceholder is a component you can change ElementRef to your component Class:
private contentPlaceholder: MyCustomComponent;
@ViewChild('contentPlaceholder') set content(content: MyCustomComponent) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}
这篇关于* ngIf中的@ViewChild的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!