如何以编程方式单击材质元素



我可以用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>

垫子凸起的按钮属性造成了问题。这是stackblitz 上的代码

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

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

分叉DEMO

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

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

有关演示,请参阅此stackblitz。

最新更新