angular - 如何在角度材料单选按钮上引发点击事件?
问题描述
我想通过按键触发点击事件,我有这个简单的组件:
<mat-radio-group [(ngModel)]="selected" aria-label="Select an option">
<mat-radio-button #first value="1">Option 1</mat-radio-button>
<mat-radio-button value="2">Option 2</mat-radio-button>
</mat-radio-group>
我想引发点击事件:
this.matRadioButton._elementRef.nativeElement.click();
但它不起作用。
解决方案
你快到了。_elementRef
您可以在_inputElement
属性上调用它,而不是调用事件。而不是直接调用click
事件,您可以使用dispatchEvent()
函数来触发事件。
尝试以下
export class RadioOverviewExample {
selected: string;
@ViewChild('first', {static: false}) matRadioButton : MatRadioButton;
constructor() {
setTimeout(() =>{
let event = new MouseEvent('click', {bubbles: true});
this.matRadioButton._inputElement.nativeElement.dispatchEvent(event);
}, 1000);
}
}
我已经修改了您的Stackblitz。
更新:触发事件监听器
由于我们触发了 on 事件this.matRadioButton._inputElement
,我们可以使用 RxJSfromEvent
函数绑定到同一个元素的点击事件。
尝试以下
import { Subject, Observable, fromEvent } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
...
export class RadioOverviewExample implements AfterViewInit, OnDestroy {
selected: string;
clickCount: number = 0; // <-- use to close open subscriptions
complete$ = new Subject<any>();
@ViewChild('first', {static: false}) matRadioButton : MatRadioButton;
constructor() {
setTimeout(() => {
let event = new MouseEvent('click', {bubbles: true});
this.matRadioButton._inputElement.nativeElement.dispatchEvent(event);
}, 1000);
}
ngAfterViewInit() {
fromEvent(this.matRadioButton._inputElement.nativeElement, 'click').pipe(
takeUntil(this.complete$)
).subscribe(
res => { this.clickCount++ } // <-- click event handler
);
}
ngOnDestroy() {
this.complete$.next(); // <-- close open subscriptions
}
}
RxJStakeUntil
运算符用于关闭ngOnDestroy()
钩子中所有打开的订阅,以避免潜在的内存泄漏。
我已经更新了你的Stackblitz。
推荐阅读
- reactjs - 反应路由器渲染组件两次
- github-pages - 如何使用 Cloudflare Worker 优化静态网站的 TTFB?
- c# - 如何将用户在文本框中输入的文本从视图传递到 asp.net 应用程序中的控制器。我在 razor 或 cshtml 中的视图
- java - JAVA上的计算器
- stripe-payments - 如何在亚洲国家/地区的 shopify 中集成软支付方式?
- ios - React Native Mapbox - 在 UIM 中找不到 MapboxNavigation
- amazon-web-services - 如何使用私有 VPC 中的 LoadBalancer 从集群外部连接到 EKS 服务
- sql - oracle中记录类型的关联数组
- regex - 删除我文件的所有部分,除了 [] 中的数据
- python - 在模板中使用 django-hosts host_url 进行 django 测试