首页 > 解决方案 > 如何在角度材料单选按钮上引发点击事件?

问题描述

我想通过按键触发点击事件,我有这个简单的组件:

<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();

但它不起作用。

堆栈闪电战

标签: angularangular-material

解决方案


你快到了。_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


推荐阅读