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.
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 .
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.
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.
@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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With