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

<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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容