Get Element using ElementRef wit

2017-07-02  本文已影响138人  RoyTien

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

<div id="my-id" #eleRef></div>

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 <variable-name>: ElementRef;
// Or
constructor( @ViewChild( "eleRef" ) private <variable-name>: ElementRef ) { }

NativeElement

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

this.<variable-name>.nativeElement.<property>/<method>
上一篇 下一篇

猜你喜欢

热点阅读