Angular: nativeElement is undefined on ViewChild

Angular

Angular Problem Overview


I want to access the DOM of a component using ViewChild. But when I try to access the nativeElement property, it's undefined.

Below is the snippet.

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { AlertComponent } from './alert.component';

@Component({
	selector: 'app-root',
	template: `
    <app-alert #alert>My alert</app-alert>
	  <button (click)="showAlert()">Show Alert</button>`
})
export class AppComponent implements AfterViewInit {
  @ViewChild('alert') alert;

  showAlert() {
    console.log('alert (showalert)', this.alert.nativeElement);
    this.alert.show();
  }
  
  ngAfterViewInit() {
    console.log('alert (afterviewinit)', this.alert.nativeElement);
  }
}

Please take a look at the plunk.

Angular Solutions


Solution 1 - Angular

If you want to get a reference of an element that hosts a component or directive you need to specify that you want the element instead of the component or directive

@ViewChild('alert', { read: ElementRef }) alert:ElementRef;

See also https://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-template/35209681#35209681

In your case I guess you need two different @ViewChild() one for the component reference to be able to access the show() method, and a 2nd one to be able to access DOM attributes.

Plunker example

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkarthikarunaView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow