在Angular/RXJS中,可以使用click事件和rxjs的fromEvent操作符来实现可点击订阅。以下是示例代码:
在组件中:
import { Component } from '@angular/core'; import { fromEvent } from 'rxjs';
@Component({
selector: 'my-component',
template:
})
export class MyComponent {
count = 0;
ngAfterViewInit() { const btn = this.myBtn.nativeElement; const btn$ = fromEvent(btn, 'click');
btn$.subscribe(() => this.count++);
} }
这个示例中,我们在组件的模板中创建了一个按钮,然后使用Angular的ViewChild装饰器来获取该元素的引用。接着,我们使用rxjs的fromEvent操作符来创建一个可观察对象btn$,并在组件的ngAfterViewInit生命周期钩子中进行订阅。每次按钮被点击时,计数器会自增1,并将新值显示在模板中的div元素中。