要解决“Angular Material按钮和RxJS fromEvent函数 - 没有nativeElement属性,只有_nativeElement属性”的问题,您可以使用@ViewChild
装饰器来获取Angular Material按钮的DOM元素,然后将其传递给fromEvent
函数进行事件绑定。
首先,在您的组件类中导入ViewChild
装饰器和ElementRef
类:
import { Component, ViewChild, ElementRef } from '@angular/core';
然后,在组件类中使用@ViewChild
装饰器来获取Angular Material按钮的DOM元素,并将其赋给buttonElement
变量:
@Component({
selector: 'app-your-component',
template: `
`,
})
export class YourComponent {
@ViewChild('myButton') buttonElement: ElementRef;
}
接下来,在ngAfterViewInit
生命周期钩子函数中使用fromEvent
函数来监听按钮的点击事件:
import { fromEvent } from 'rxjs';
export class YourComponent implements AfterViewInit {
@ViewChild('myButton') buttonElement: ElementRef;
ngAfterViewInit() {
const buttonClick$ = fromEvent(this.buttonElement.nativeElement, 'click');
buttonClick$.subscribe(() => {
console.log('Button clicked');
});
}
}
现在,当按钮被点击时,您将在控制台上看到“Button clicked”的输出。
请注意,从Angular 8开始,@ViewChild
装饰器默认情况下使用查询结果的第一个匹配项。如果您的模板中有多个具有相同引用的按钮,请确保使用@ViewChildren
装饰器来获取所有匹配项的数组,并相应地进行处理。