如何在 ng2 中获取 组件的 DOM 元素

可以通过注入ElementRef,访问nativeElement属性获取原始DOM

import{Component,ElementRef}from'angular2/core';@Component({    selector:'App',    providers:[],    template:`

{{content}}

`})exportclassApp{    content:string='Hello Kittencup';constructor(publicelementRef:ElementRef){console.log(elementRef.nativeElement);    }ngAfterViewInit(){console.log(this.elementRef.nativeElement);    }}

在constructor里获取的时候,template中得变量还未被渲染出来,这时候DOM结构是

在ngAfterViewInit周期中,如果对组件的生命周期还不了解的话,可以看下这里生命周期钩子,template已经被渲染出来了,这时候DOM结构是

   

Hello Kittencup

你可以根据你的需求选择不同时期的DOM

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容