I have an Angular component and in its template I have placed an Angular Material button, i.e. something like <button #myButton mat-button></button>.
Now what I want to do is to get hold of this button in my code, generate an Observable that emits when the button is clicked and happily do whatever I need to do with such Observable.
First thing: I get hold of the button using @ViewChild with the following code
@ViewChild('myButton') myButton: MatButton;
I specify the type of the variable as MatButton since it is actually of that type.
And eventually my problem. I would like to use my usual approach, i.e. use fromEvent(this.myButton.elementRef.nativeElement, 'click')in the ngAfterViewInit method. Unfortunately I get an error Invalid event target. Digging a bit I find that MatButton does not have a property elementRef but it has a property named _elementRef. From the leading underscore this sounds like a private property, but I did not find any better way to create an Observable starting from a MatButton directive and using fromEvent function of RxJS.
Any suggestion would be appreciated.
You can access the ElementRef of the button with the read option of ViewChild:
@ViewChild("myButton", { read: ElementRef }) myButtonRef: ElementRef;
ngOnInit() {
console.log(this.myButtonRef.nativeElement);
...
}
See this stackblitz for a demo and this article for more info about ViewChild.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With