问题描述
@ViewChild
装饰器是否有一些方法可以像角度6的旧ngOnInit
中一样,获得@ViewChild
中子组件的实例?
我尝试过类似的事情:
@Component({
....
})
export class AppComponent implements OnInit {
@ViewChild(HelloComponent,{static: true})
@ViewChild(HelloComponent,{static: false})
hello: HelloComponent;
ngOnInit() {
console.log('Hello Instance',this.hello);
}
}
解决方法
尝试一下:
static: true
根据经验,您可以进行以下操作:
要在ngOnInit中访问ViewChild时,需要设置 { static: true }
。
{ static: false }
仅可在ngAfterViewInit中访问。这也是你想要的
有结构指令时就去找
我想与其他读者分享我刚刚为@ViewChild 发现的知识
让@ViewChild 在static
中将ngOnInit
属性设置为false
我必须像这样把它放在 setTimeout() 中:
@ViewChild(HelloComponent,{static:false}) hello: HelloComponent;
ngOnInit() {
setTimeout(() => {
console.log('Hello Instance',this.hello);
},100);
}
这样就可以拿到ngOnInit
里面的子组件