1

Framework: Angular 8

Might I am missing up some thing, I need to get the width of element and set the width of child element divide by 5.

My First attempt to get the value from @ViewChild, but getting error.

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>

2nd Attempt through String interpol

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

(Width is divide with 5 and due to margin I subtract 25)

In 2nd attempt, I got what I need, but getting this Error.

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

Can some buddy tell me what I am getting Native Element error in first attempt and how to fix 2nd attempt code, so there will be no error.

user12552117
  • 109
  • 2
  • 10

1 Answers1

2

You will only have access to it in ngAfterViewInit that gets called once the view for the component is initialized.

Try accessing the nativeElement in the ngAfterViewInit lifecycle hook method:

ngAfterViewInit() {
    /* Query Bar */
    this.qrycontainerWidth = this.qrywrapper.nativeElement.offsetWidth;
    console.log(this.qrycontainerWidth, "container width");
    /* Query Bar end */
}
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • 1
    great thanks :), can you tell me solve error in 2nd attempt? – user12552117 Dec 22 '19 at 10:24
  • Give **[this answer a try to fix that](https://stackoverflow.com/a/35243106/2622292)** and if you want to know more about the reason for it, please check **[this article](https://blog.angular-university.io/angular-debugging/)** out – SiddAjmera Dec 22 '19 at 10:28