在 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
导入 ViewChild
、ElementRef
以及 Component
和 AfterViewInit
。
在我们将它们导入到我们的类之后,在 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>
输出:
使用这些简单的步骤,我们可以使用其 ElementRef
操作任何 DOM 元素。
如果我们想要替换元素而不是仅仅改变按钮的名称,我们可以使用 outerHTML
。
在 ngAfterViewInit()
中,编写以下代码以将按钮替换为标题。
# Angular
btnElement.outerHTML = '<h1>This is Heading</h1>';
输出:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。