在Angular中,可以使用@ViewChild
装饰器来获取当前元素的引用,并通过.nativeElement
属性来访问该元素的属性。
以下是一个示例代码:
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-example',
template: `
`
})
export class ExampleComponent {
@ViewChild('myButton', { static: true }) myButton: ElementRef;
handleClick(event: MouseEvent) {
const target = event.currentTarget as HTMLButtonElement;
console.log(target.textContent); // 输出:Click me
// 使用ViewChild获取的元素引用
const nativeElement = this.myButton.nativeElement as HTMLButtonElement;
console.log(nativeElement.textContent); // 输出:Click me
}
}
在上述代码中,我们使用@ViewChild
装饰器来获取模板中的myButton
元素的引用,并在handleClick
方法中访问了currentTarget
属性的值。另外,我们也通过this.myButton.nativeElement
来访问myButton
元素的属性。注意要进行类型断言,将其转换为HTMLButtonElement
类型。