Search code examples
angularviewchild

Native Element is not defined in angular 8


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.


Solution

  • 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 */
    }