如何将代码从 JavaScript 更改为 Angular/Typescript 方式

How to change the code from JavaScript to the Angular/Typescript way

我有这个代码:

app.component.ts

    export class AppComponent implements AfterViewInit {

      targetElement: HTMLElement;
      viewer: any;

      constructor () {}

      ngAfterViewInit() {
       this.targetElement = document.getElementById('wrapper'); // This line
      }


  app.component.html



    <div #wrapper id="wrapper" [innerHTML]=targetElement></div>

我不想用

document.getElementById('wrapper');

是否有 Angular 方法来更改标记为:// This line 的行?

如果您想访问 dom,可以使用模板引用。

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

export class AppComponent implements AfterViewInit {

  @ViewChild('wrapper')
  wrapper: ElementRef
  viewer: any;

  constructor () {}

  ngAfterViewInit() {
  }

}


  <div #wrapper></div>

this.wrapper 将具有可用于访问

的 dom 节点

Angular 方法是使用带有 @ViewChild 装饰器的模板引用

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

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

  constructor() {}

  ngAfterViewInit() {
   //use this.test
  }
}

注意这一行@ViewChild('#wrapper') test: ElementRef; wrapper 引用 html 元素上的模板引用

另一种方法是直接在 constructor 中注入 ElementRef

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

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

  constructor(private elem: ElementRef) {}

  ngAfterViewInit() {
    this.elem.nativeElement.querySelector('#wrapper');
  }
}