ViewChild returns 未定义

ViewChild returns undefined

我正在使用 material 设计和 Angular 5。我正在尝试使用 material 加载器,所以当导航开始时显示加载器,当结束时根据答案删除加载器在 。我试过 viewchild

<mat-progress-bar #spinnerElement [mode]="'indeterminate'" [color]="'primary'"></mat-progress-bar>

并在我的组件构造函数中调用如下:

@ViewChild('spinnerElement')
spinnerElement: ElementRef;

constructor(
.....
    private ngZone: NgZone,
    private renderer: Renderer) {
        console.log(this.spinnerElement, 'spinnerElement');
    }

但控制台总是 returns undefined。 Angular 有点新。知道为什么吗?

看看angular life cycle.

您无法在构造函数中访问 DOM 元素,因为它们仍未呈现。

尝试在您的 ngOnInit() 中访问您的 'spinnerElement'。

ngOnInit():

Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties. Called once, after the first ngOnChanges().

ngOnInit()中访问@ViewChild,初始化前不能使用。