Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Button and RxJS fromEvent function - there is no nativeElement property but just _nativeElement property

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.

like image 887
Picci Avatar asked Jan 20 '19 21:01

Picci


1 Answers

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.

like image 57
ConnorsFan Avatar answered Sep 27 '22 19:09

ConnorsFan