2016-11-26 22 views
2

私は直接操作したいng2コンポーネントの要素を持っています。そのプロパティが2秒ごとに更新されるため、そのプロパティがフレームワークによって処理される必要はありません。また、ライフサイクルに影響を与えたくないためです。私のの例では(実際のユースケースではありません)では、毎秒増分するタイマーを使用します。角度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を使用して、コンポーネント内の要素を取得できます。あなたはタイマーを取得し、(これは確か要素がレンダリングされている作ることAfterViewInitであることに注意してレンダラを使用して、それを操作することができるコンポーネントに続いて

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

:たとえばタイマーのdivのテンプレートのref #timerを設定):

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! –

関連する問題