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