2017-03-04 75 views
11

我有一个Angular 2组件,我想通过它的id检索元素div <div id ="myId">。我尝试在我的组件(TypeScript)中执行:document.getElementById("myId"),但出现错误:“无法找到名称文档”。我发现在其他帖子中,我们可以使用@ViewChild做类似的事情,但是我不明白我们如何使用div来创建任何想法?Angular 2:访问组件中的元素,getDocumentById不起作用

+0

你能告诉你的代码 – Gab

回答

16

你可以通过添加一个TemplateRef来使用带div的@ViewChild。

模板

<div id ="myId" #myId> 

组件

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; 

    @Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
    }) 
    export class AppComponent implements AfterViewInit { 
    @ViewChild('myId') myId: ElementRef; 

    constructor() { 
    } 

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

This blog post卡拉埃里克森是越来越熟悉角的方法来这样搞真的很好看。

+0

谢谢!这工作! :) – eagleEye

6

模板引用变量添加的元素,你需要访问:

<div #myDiv></div> 

而在组件:

class MyComponent implements AfterViewInit { 
    @ViewChild('myDiv') myDiv: ElementRef; 

    constructor() {} 

    ngAfterViewInit() { 
     console.log(this.myDiv); 
    } 
}