2
votes

I can programatically click a button element with elementref but if a button were of material button then it doesn't work

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

and in the template,

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

The mat-raised-button attribute is creating the issue. Here is the code on stackblitz

2

2 Answers

1
votes

Use MatButton as its type instead of ElementRef

@ViewChild('findButton') findButton: MatButton;
clicked() {
  console.log('clicked');
}

ngOnInit() {
  this.findButton._elementRef.nativeElement.click();
}

Forked DEMO

1
votes

You can retrieve the ElementRef associated with the MatButton with the following syntax:

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

See this stackblitz for a demo.