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

mic*_*cah 3 angular

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

HTML的

<div class="timer"></div>
<div>Elapsed</div>
Run Code Online (Sandbox Code Playgroud)

零件-

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

}
Run Code Online (Sandbox Code Playgroud)

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

Jay*_*ase 5

您可以使用ViewChild和模板引用变量来获取组件中的元素.例如,在计时器div上设置模板ref #timer:

<div class="timer" #timer></div>
<div>Elapsed</div>
Run Code Online (Sandbox Code Playgroud)

然后在组件中,您可以获取计时器并使用Renderer对其进行操作(请注意,这是在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');
    }
  }
Run Code Online (Sandbox Code Playgroud)