HOWTO · Angular

Angular 中的 getElementById 替代

本教程演示了如何在 Angular 中通过 id 获取元素。

本页内容

我们将介绍 Angular 中 getElementById 函数的替代。

我们还将在 Angular 中引入 ElementRef 函数以从输入中获取文档的元素引用和值。

Angular 中的 getElementById 替代

getElementById 方法返回具有指定值的 ID 属性的元素。这种方法在 HTML DOM 中最常见,几乎每次我们操作、获取信息或文档中的元素时都会用到。

因为 getElementById 是 vanilla Javascript 函数并且我们在 Angular 中使用 Typescript,所以 Typescript 中这个函数的替代是 ElementRef,我们将在本教程中介绍。

Angular 中的 ElementRef

ElementRef 是一个类,它可以包裹指定的 DOM 元素以增强本机元素的方法和属性。如果我们将元素定义为 ElementRef,我们可以将其作为 nativeElement 对象访问。

本文与 Angular 4 到 Angular 12 兼容。

让我们在带有@ViewChild 装饰器的类中使用 ElementRef Interface 来获取元素引用。

首先,我们将编辑我们的 app.component.html 模板并向其中添加以下代码。

# angular

<div #myNameElem></div>

<button (click)="getValue()">Get Value</button>

输出:

ElementRef Angular 的第一个示例

在 app.component.ts 文件中,我们将添加以下内容。

#angular
import { Component, VERSION, ViewChild, ElementRef } from "@angular/core";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})

export class AppComponent {
  name = "Angular " + VERSION.major;
  @ViewChild("myNameElem") myNameElem: ElementRef;
  getValue() {
    console.log(this.myNameElem);
    this.myNameElem.nativeElement.innerHTML = "I am changed by ElementRef & ViewChild";
  }
}

输出:

Angular 中的元素引用

在 Angular 中使用 ElementRef 从输入中获取值

现在我们将介绍如何在 Angular 中使用 ElementRef 获取输入的值。

首先,我们将编辑我们的 app.component.html 模板并向其中添加以下代码。

# angular
<input type="text" name="name" #myNameElem />
<button (click)="getValue()">Get Value</button>
<button (click)="resetValue()">Reset</button>

输出:

Angular 中 ElementRef 的第二个示例

现在,在 app.component.ts 文件中,我们将添加以下内容:

#angular
import { Component, VERSION, ViewChild, ElementRef } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  @ViewChild('myNameElem') myNameElem: ElementRef;
  getValue() {
    console.log(this.myNameElem.nativeElement.value);
  }
  resetValue() {
    this.myNameElem.nativeElement.value = '';
  }
}

输出:

Angular 中的 ElementRef 示例