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 示例