2017-03-04 74 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); 
    } 
}