2016-11-26 66 views
2

我有一个ng2组件中的元素,我想直接操作。我不需要或者不希望它的属性被框架处理,因为它的属性将在逐秒的基础上更新,我不希望它影响生命周期。在我的示例(不是实际的用例)中,我将使用每秒递增的计时器。角2分量中的参考特定元素?

HTML的

<div class="timer"></div> 
<div>Elapsed</div> 

成分 -

@Component({ 
    selector: 'timer', 
    templateUrl: 'timer.html', 
}) 
export class TimerComponent { 

    private time = 0; 

    // How do I get .timer ? 
    constructor(private $element: ElementRef) {} 

    onNgInit() { 
    setInterval(this.incrementTimer.bind(this), 1000); 
    } 

    private incrementTimer() { 
    this.time++; 
    this.$element.nativeElement.innerHTML = this.time; 
    } 

} 

我有很多的选择,以得到定时器元素,但我不知道是否有一种简单的方法(角路)标记元素,以便角度理解/将其包含在喷射器中。我不想在DOM中搜索这个元素,而且我更喜欢每次我想更新时都不要点击生命周期。

回答

4

您可以使用ViewChild和template reference variable来获取组件中的元素。例如设置定时器DIV模板裁判#timer:

<div class="timer" #timer></div> 
<div>Elapsed</div> 

然后在组件,您可以得到定时器,并使用渲染器(注意,这是在AfterViewInit以确保元素被渲染操纵它):

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

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

    constructor(private renderer: Renderer) { } 

    ngAfterViewInit() { 
     this.renderer.setElementProperty(this.timer.nativeElement, 'innerText', 'hello'); 
    } 
    } 
+0

我在想''''关键字是干什么用的。这是有道理的。谢谢,JayChase! –