在Angular中,可以使用fromEvent
操作符从事件监听器中返回一个可观察对象。以下是一个例子:
import { Component, OnInit, ElementRef } from '@angular/core';
import { fromEvent } from 'rxjs';
@Component({
selector: 'app-example',
template: '',
})
export class ExampleComponent implements OnInit {
constructor(private elementRef: ElementRef) {}
ngOnInit() {
const button = this.elementRef.nativeElement.querySelector('button');
fromEvent(button, 'click').subscribe(event => {
console.log('Button clicked');
});
}
onClick() {
// Do something when the button is clicked
}
}
在上面的例子中,我们在ngOnInit
生命周期钩子中使用fromEvent
操作符从按钮的click
事件监听器中创建一个可观察对象。然后,我们订阅这个可观察对象,并在回调函数中打印"Button clicked"。