📅  最后修改于: 2023-12-03 14:59:11.422000             🧑  作者: Mango
在Angular中,可以通过元素引用来获取DOM元素,并对其进行一些操作。可以使用@ViewChild
装饰器来声明元素引用,并在组件的构造函数中注入ElementRef
来获取对应的DOM元素。
一般情况下,我们需要向DOM元素添加class来实现一些视觉效果,比如高亮、隐藏等。以下是如何向元素引用添加class的示例代码:
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
template: `<button #btn (click)="onButtonClick()">点击我</button>`
})
export class AppComponent {
@ViewChild('btn') buttonRef: ElementRef;
onButtonClick() {
const buttonElement = this.buttonRef.nativeElement;
buttonElement.classList.add('btn-primary');
}
}
在上述代码中,@ViewChild
装饰器声明了一个名为buttonRef
的元素引用,它绑定到了<button>
元素上。在onButtonClick()
方法中,我们获取了buttonRef
的nativeElement属性,这是一个指向DOM元素的引用。我们调用该DOM元素的classList.add()
方法来向它添加btn-primary
的class。
以上代码片段应该按照Markdown格式进行排版。