Get Element using ElementRef with ViewChild

From: https://stackoverflow.com/questions/39256703/angular-2-viewchild-returns-undefined
Author: Aviad P.


Use this ElementRef API as the last resort when direct access to DOM is needed.

Import ElementRef and ViewChild Decorators from '@angular/core'

ElementRef injects into the directive's constructor so the code can access the DOM element.

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

Set ElementRef for an element

ElementRef provides access to the underlying native element (DOM element).

Using #eleRef, '-' is not allowed in reference names.

The eleRef will be used by @ViewChild decorator

Get Element variable with ViewChild

You can use ViewChild to get the first element or the directive matching the selector from the view DOM.

Forgot to mention that any view child thus declared is only available after the view is initialized. The first time this happens is in ngAfterViewInit (import and implement the OnAfterViewInit interface).
Do not forget private
The ref name must be in camel case or this will not work.

@ViewChild( "eleRef" ) private : ElementRef;
// Or
constructor( @ViewChild( "eleRef" ) private : ElementRef ) { }

NativeElement

ElementRef is a service that grants direct access to the DOM element through its nativeElement property.

this..nativeElement./

你可能感兴趣的:(Get Element using ElementRef with ViewChild)