I am trying to setup a click event to a Button dynamically using fromEvent
and defer
modules of rxjs
.
It works fine when using normal html button, but doesn't work with Angular Material button.
Here is the code works fine with Normal Button:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { defer, fromEvent } from 'rxjs';
import { map, tap } from 'rxjs/operators';
@Component({
selector: 'app-test',
template: `
<button #testBtn>Click me</button>
`
})
export class TestComponent implements OnInit {
@ViewChild('testBtn', { static: true }) testBtn: ElementRef<HTMLButtonElement>;
event$ = defer(() => fromEvent(this.testBtn.nativeElement, 'click')).pipe(
map(() => new Date().toString()),
tap(console.log)
)
constructor() { }
ngOnInit() {
this.event$.subscribe();
}
}
And here is the code which doesn't work with Angular Material Button
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { defer, fromEvent } from 'rxjs';
import { map, tap } from 'rxjs/operators';
@Component({
selector: 'app-test',
template: `
<button mat-raised-button #testBtn>Click me</button>
`
})
export class TestComponent implements OnInit {
@ViewChild('testBtn', { static: true }) testBtn: ElementRef<HTMLButtonElement>;
event$ = defer(() => fromEvent(this.testBtn.nativeElement, 'click')).pipe(
map(() => new Date().toString()),
tap(console.log)
)
constructor() { }
ngOnInit() {
this.event$.subscribe();
}
}
I couldn't guess why this problem is happening.
Can you help me understand it ?
EDIT: add it { read: ElementRef }
your ViewChild;
Use it for your matButton. @ViewChild("myButton", { read: ElementRef }) myButtonRef: ElementRef; You need to use your button as nativeElement ElementRef;