Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Imporial opened this issue Jan 17, 2016 · 1 comment
Open

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

Imporial opened this issue Jan 17, 2016 · 1 comment

Comments

@Imporial
Copy link

用 mdl 的界面包,动态加载 mdl 控件时必须获取 mdl 控件元素对其手动注册,ng2 中如何获取 DOM 元素

@kittencup
Copy link
Owner

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

import {Component,ElementRef} from 'angular2/core';
@Component({
    selector: 'App',
    providers: [],
    template: `
        <h1>{{content}}</h1>
    `
})
export class App {

    content:string = 'Hello Kittencup';

    constructor(public elementRef:ElementRef){
        console.log(elementRef.nativeElement);
    }

    ngAfterViewInit(){
        console.log(this.elementRef.nativeElement);
    }
}

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

<app>
    <h1></h1>
</app>

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

<app>
    <h1>Hello Kittencup</h1>
</app>

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants