Trying to create an input with a clear button following the example from Angular Material, link to the example, what I want is to get the input value on a keypress enter event.
HTML:
<mat-form-field>
<input matInput (keydown.enter)="applyFilter($event)" placeholder="Search"
name="search" [(ngModel)]="searchValue">
<button mat-icon-button matSuffix aria-label="Clear" (click)="clearSearch()">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>
TS:
applyFilter(event: any) {
console.log(JSON.stringify(event));
}
Results of the console when printing the event content:
{"isTrusted":true}
Check the event. And the following JavaScript code to detect whether the Enter key is pressed: const input = document. querySelector("input"); input. addEventListener("keyup", (event) => { if (event.
you can easily use keypress event in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 application. When user will press key on input box field then trigger onKeypressEvent() of angular component. we will use (change) attribute for call function.
(keyup. enter) event is used to generate event when Enter key is pressed.
Im not familiar with this specific scenario of the component from Material Design, But the suggestions in the comments are the traditional way to do it.
There might be an interruption from the MD component with the event, so you can try to manually pass the value to the function. something like this:
<mat-form-field>
<input matInput #txtVal (keydown.enter)="applyFilter(txtVal.value)" placeholder="Search"
name="search" [(ngModel)]="searchValue">
<button mat-icon-button matSuffix aria-label="Clear" (click)="clearSearch()">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>
TS:
applyFilter(val: string) {
console.log(val);
}
#txtVal
is just a local variable in the input field, so we pass its value manually to the function.
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