Angular 2组件中的参考特定元素?

时间:2016-11-26 03:09:10

标签: angular

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

HTML -

@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;
  }

}

组件 -

app.run(debug=True)

我有很多选项来获取计时器元素,但我想知道是否有一种简单的方法(一种有角度的方式)来标记元素,以便角度理解/包含它在注射器中。我不想在DOM中搜索此元素,而且我不想在每次要更新时都使用生命周期。

1 个答案:

答案 0 :(得分:5)

您可以使用ViewChild和template reference variable来获取组件中的元素。例如,在计时器div上设置模板ref #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');
    }
  }