Angular 中的 ElementRef
Rana Hasnain Khan
2024年2月15日
Angular
Angular ElementRef
我們將介紹什麼是 ElementRef 以及如何在 Angular 中使用它。
在 Angular 中使用 ElementRef 獲取 DOM 元素
ElemenRef 是包含屬性 nativeElement 的原生 DOM 元素物件的包裝器。它持有對 DOM 元素的引用,我們可以使用它來操作 DOM。它與 ViewChild 一起用於從元件類中獲取 HTML 元素。
讓我們通過一個例子來詳細瞭解 ElementRef 並知道如何在我們的應用程式中使用它。
首先,我們需要從 app.component.ts 檔案中的@angular/core 匯入 ViewChild、ElementRef、Component 和 AfterViewInit。
匯入它們後,我們將在我們的類中使用 ViewChild 建立一個 ElementRefDiv。我們將建立一個 ngAfterViewInit 函式,將值傳遞給我們的 div。
所以我們在 app.component.ts 中的程式碼將如下所示。
# angular
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
@ViewChild('ElementRefDiv') ElementView: ElementRef;
ngAfterViewInit() {
console.log(this.ElementView);
this.ElementView.nativeElement.innerHTML = 'Hello I am Using ElementRef To Display this!';
}
}
我們需要在 app.component.html 中建立一個帶有 ElementRefDiv 類的模板。
# angular
<div #ElementRefDiv></div>
輸出:

因此,通過這些簡單的步驟,我們可以使用其 ElementRef 和 ViewChild 操作任何 DOM 元素。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn