Cannot read property 'native-element' of undefined

I think you are tring to get the value from html before rendering completely. If you try to print the value in a button click, it will works.

depend on your code I have modified a little.Try the below, it is working for me.

  ngAfterViewInit() {
    console.log("afterinit");
    setTimeout(() => {
      console.log(this.abc.nativeElement.innerText);
    }, 1000);
  }

Note: If not working, please increase the timeout time and try again.


Note for those who wonder, when using ViewChild in newer Angular (8+) you might get this error if you are trying to use ViewChild on a dynamically rendered object while using static flag.

example: @ViewChild('someSection',{ static: false }) someSection: ElementRef;

The { static: true } option was introduced to support creating embedded views on the fly. When you are creating a view dynamically and want to acces the TemplateRef, you won't be able to do so in ngAfterViewInit as it will cause a ExpressionHasChangedAfterChecked error. Setting the static flag to true will create your view in ngOnInit.

Credit to Poul Krujit here for pointing this out: How should I use the new static option for @ViewChild in Angular 8?


you can use the ElementRef in conjunction with @ViewChild if you do the following

HTML Markup:

<input type="text" class="form-control" #someNameInput>
<button
  class="btn btn-primary"
  (click)="clickMe()">Click Me</button>

In the Component Code:

@ViewChild('someNameInput',{static: true}) someNameInput: ElementRef;

For older version it's

@ViewChild('someNameInput') someNameInput: ElementRef;

Right before the constructor() method

And here is how you would use it in a function

clickMe(){
console.log(this.someNameInput.nativeElement.value);

}

If you get some value is undefined, it's usually means that it's a JavaScript issue and you don't have something initialized. Try and take ViewChild out of the equation first and make sure the code works without it first. Then introduce ViewChild into the mix. Kind of like testing your API with postman first then doing the Angular code later. Make sure that backend works first then you know for sure it's the Angular code. Angular has different page life cycles so some values are only available in the onAfterViewInit event and not on other events. So you have to play around with the view cycles. Haven't tried it but I suspect that if you try to get the value of the ViewChild in the ngOnInit method you will get an error or a blank value.


The best lifecycle hook to use is AfterContentInit, allow all of the html content (such as the #map_canvas div) to be found by the scripts.

import { AfterContentInit, ViewChild } from '@angular/core';

Also, some updates have been made to ViewChild, it now takes a 2nd parameter:

@ViewChild('map_canvas', {static: false}) map_canvas: ElementRef;

Now you can use that hook to initialize your map:

ngAfterContentInit() {
    this.loadMap();
}