【问题标题】:How to programmatically click a material element?如何以编程方式单击材质元素?
【发布时间】:2019-04-11 01:35:40
【问题描述】:

我可以通过 elementref 以编程方式单击按钮元素,但如果按钮是实体按钮,则它不起作用

@ViewChild('findButton') findButton: ElementRef;
  clicked() {
  console.log('clicked');
}
ngOnInit() {
  this.findButton.nativeElement.click()
}

在模板中,

<div class="example-button-row">
  <button #findButton (click)="clicked()" mat-raised-button color="primary">Primary</button>
</div>

mat-raised-button 属性造成了问题。这是stackblitz上的code

【问题讨论】:

    标签: angular


    【解决方案1】:

    使用MatButton 作为其类型而不是ElementRef

    @ViewChild('findButton') findButton: MatButton;
    clicked() {
      console.log('clicked');
    }
    
    ngOnInit() {
      this.findButton._elementRef.nativeElement.click();
    }
    

    分叉DEMO

    【讨论】:

    • 谢谢。我担心我不能接受多个答案。
    【解决方案2】:

    您可以使用以下语法检索与MatButton 关联的ElementRef

    @ViewChild('findButton', { read: ElementRef }) findButton: ElementRef;
    

    请参阅this stackblitz 以获取演示。

    【讨论】:

      猜你喜欢
      • 2010-10-22
      • 2021-06-20
      • 1970-01-01
      • 2011-07-15
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      相关资源
      最近更新 更多