Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: nativeElement is undefined on ViewChild

Tags:

angular

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.

like image 915
karthikaruna Avatar asked Aug 28 '17 14:08

karthikaruna


People also ask

Why is my ViewChild undefined?

The problem can be caused by the *ngIf or other directive. The solution is to use the @ViewChildren instead of @ViewChild and subscribe the changes subscription that is executed when the component is ready. For example, if in the parent component ParentComponent you want to access the child component MyComponent .

What is nativeElement in angular?

Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.

What does ViewChild return?

ViewChild returns the first matching element and ViewChildren returns all the matching elements as a QueryList of items. We can use these references to manipulate element properties in the component.

How do you declare a ViewChild?

@ViewChild() using Directive@ViewChild() can instantiate a directive within a component and in this way the component will be able to access the directive methods. Here we will create a directive that will contain the methods to change the text color of the host element of DOM layout. Find the directive.


1 Answers

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 angular 2 / typescript : get hold of an element in the template

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

like image 78
Günter Zöchbauer Avatar answered Sep 19 '22 08:09

Günter Zöchbauer