在 Angular 中按类名查找元素

Rana Hasnain Khan 2024年2月15日
在 Angular 中按类名查找元素

我们将介绍 ElementRef 以及如何使用它在 Angular 中按类名查找元素。

在 Angular 中使用 ElementRef 按名称查找类

ElementRef 是一个包含 nativeElement 属性的原生 DOM 元素对象包装器。它持有对 DOM 元素的引用并使用它来操作 DOM。

它与 ViewChild 一起使用以从组件类中获取 HTML 元素。让我们通过一个例子来理解使用 ElementRef 对象。

使用以下命令在 Angular 中创建一个新应用程序。

# angular
ng new my-app

创建应用程序后,使用此命令转到应用程序的目录。

# angular
cd my-app

让我们运行我们的应用程序来检查所有依赖项是否都安装正确。

# angular
ng serve --open

首先,我们需要从 app.component.ts 文件中的@angular/core 导入 ViewChildElementRef 以及 ComponentAfterViewInit

在我们将它们导入到我们的类之后,在 constructor 中创建一个私有 ElByClassName 和一个 ngAfterViewInit 函数,该函数将使用 <HTMLElement> 通过类名保存我们获得的元素。

一旦我们有了我们想要的元素,我们现在可以使用 innerHTML 更改按钮的名称。app.component.ts 中的代码如下所示。

# angular
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular';
constructor(private ElByClassName: ElementRef) {}
ngAfterViewInit() {
const btnElement = (<HTMLElement>this.ElByClassName.nativeElement).querySelector(
'.myButton'
);
btnElement.innerHTML = 'This is Button';
}
}

我们需要在 app.component.html 中创建一个带有 myButton 类的按钮模板。

# angular
<button class="myButton">My Button</button>

输出:

在 Angular 中按类名查找元素

使用这些简单的步骤,我们可以使用其 ElementRef 操作任何 DOM 元素。

如果我们想要替换元素而不是仅仅改变按钮的名称,我们可以使用 outerHTML

ngAfterViewInit() 中,编写以下代码以将按钮替换为标题。

# Angular
btnElement.outerHTML = '<h1>This is Heading</h1>';

输出:

在 Angular 中按类名查找元素并替换它

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

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

相关文章 - Angular Element