Reputation: 515
I'm trying to simulate a click on a button in Angular. But it's not working. I imported ViewChild
and ElementRef
. Then added the hash reference to the button. and then called the click but it's not working. this is the HTML:
<button #filterPanelButton id="loadFiltersButton" class="details-filters-button" mat-button [ngClass]="{'filter-button-active': loadButtonChanged}"
type="button"[matMenuTriggerFor]="loadDetailsFilter" (menuOpened)="detailsFiltersOpened()">
<span id="loatFilterButtonText" class="details-filters-button-text">{{loadButtonText}}</span>
<mat-icon class="menu-active" [ngClass]="{'menu-open': arrowUp}">arrow_drop_down</mat-icon>
</button>
and this is the .ts method:
lauchSearchAndCLoseFiltersPanel($event){
this.detailsFiltersClosed($event);
// document.getElementById('loadFiltersButton').click();
this.filterPanelButton.nativeElement.click();
}
If I uncomment the document.getElementById('loadFiltersButton')
it works, but I've heard that it is discouraged to use that method in Angular.
Why might the viewChild method not be working?
Upvotes: 2
Views: 2151
Reputation: 44326
You probably got the MatButton
class but in your case you need to make sure that you get the ElementRef
from your @ViewChild
decorator. To do that you can pass a second argument with a read
property and explicitly set it to ElementRef
like so:
@ViewChild('filterPanelButton', { read: ElementRef }) public filterPanelButton: ElementRef;
And now this should work:
this.filterPanelButton.nativeElement.click();
See also the answer on a similar question here.
Check for more information about the ViewChild
and its read
property also the official Angular documentation here.
read - Used to read a different token from the queried elements.
So if you're querying a MatButton
with your selector (or another material component), you won't be able to get the nativeElement
since you get the reference to the material component and not to the ElementRef
.
Upvotes: 2
Reputation: 12001
the correct way would be not to work with low level events, but to call the openMenu
@ViewChild(MatMenuTrigger) trigger
lauchSearchAndCLoseFiltersPanel(){
this.trigger.openMenu();
}
Upvotes: 2