美文网首页
Get Element using ElementRef wit

Get Element using ElementRef wit

作者: RoyTien | 来源:发表于2017-07-02 17:49 被阅读138次

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>

相关文章

网友评论

      本文标题:Get Element using ElementRef wit

      本文链接:https://www.haomeiwen.com/subject/phfocxtx.html