[英]ViewChild returns undefined
I am using material design and Angular 5. I was trying to use the material loader, so when navigation start show loader and when ends remove loader as per the answer in this question . 我正在使用材质设计和Angular5。我试图使用材质加载器,因此,按照此问题的答案,在导航开始时显示显示加载器,并在结束时删除加载器。 I tried
viewchild
by 我尝试过
viewchild
<mat-progress-bar #spinnerElement [mode]="'indeterminate'" [color]="'primary'"></mat-progress-bar>
and called in my component constructor as below: 并在我的组件构造函数中调用,如下所示:
@ViewChild('spinnerElement')
spinnerElement: ElementRef;
constructor(
.....
private ngZone: NgZone,
private renderer: Renderer) {
console.log(this.spinnerElement, 'spinnerElement');
}
But console always returns undefined
. 但是控制台始终返回
undefined
。 Bit new to Angular. 对Angular有点陌生。 Any idea why guys?
知道为什么吗?
Take a look at angular life cycle . 看一下角度生命周期 。
You can't access your DOM elements in your constructor because they still not rendered. 您无法在构造函数中访问DOM元素,因为它们仍未呈现。
Try to access your 'spinnerElement' in your ngOnInit(). 尝试在ngOnInit()中访问“ spinnerElement”。
ngOnInit(): ngOnInit():
Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.
在Angular首先显示数据绑定属性并设置指令/组件的输入属性后,初始化指令/组件。 Called once, after the first ngOnChanges().
在第一个ngOnChanges()之后调用一次。
在ngOnInit()
访问@ViewChild
在初始化之前不能使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.