angular 8 中未定义原生元素

Native Element is not defined in angular 8

框架:Angular8

可能我遗漏了什么,我需要获取元素的 width 并设置子元素的 width 除以 5

我第一次尝试从 @ViewChild 获取值,但出现错误。

ERROR TypeError: Cannot read property 'nativeElement' of undefined.

code.ts

@ViewChild("qrywrapper", { static: false }) qrywrapper: ElementRef;
qrycontainerWidth;
constructor() {}
ngOnInit() {
    /* Query Bar */
    this.qrycontainerWidth = this.qrywrapper.nativeElement.offsetWidth;
    console.log(this.qrycontainerWidth, "container width");
    /* Query Bar end */
}

html

<div class="mx-3 flex-grow-1" #qrywrapper>
  <span [ngStyle]="{ 'width.px' : qryWidth }"></span>
</div>

第二次尝试通过字符串 interpol

<div class="mx-3 flex-grow-1" #qrywrapper>
  <span [ngStyle]="{ 'width.%' : (qrywrapper.offsetWidth/5)-25 }"></span>
</div>

(宽度除以 5,由于边距我减去 25)

在第二次尝试中,我得到了我需要的东西,但是出现了这个错误。

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'width.%: 218.8'. Current value: 'width.%: 218.2'.

哪位朋友能告诉我我在第一次尝试时遇到的 Native Element 错误以及如何修复第二次尝试的代码,这样就不会出现错误了。

您只能在组件视图初始化后调用的 ngAfterViewInit 中访问它。

尝试在 ngAfterViewInit 生命周期挂钩方法中访问 nativeElement

ngAfterViewInit() {
    /* Query Bar */
    this.qrycontainerWidth = this.qrywrapper.nativeElement.offsetWidth;
    console.log(this.qrycontainerWidth, "container width");
    /* Query Bar end */
}