Question: why is the event only returning the first letter of input form.
Background: There is a input form in which a user can type a string into. The method I created that handles the event is only capturing the first letter entered. So for example someone types in "hello" and the method will fire and event handler in this order 'h' 'e' 'l' 'l' 'o'
I have tried to capture the value and push it to array but in every attempt I have not achieved the intended outcome.
Intended outcome: I would like to capture the letters in a method that would dynamically store it in an array, so if someone deletes a character that would be reflected.
The template
<mat-form-field appearance="outline" >
<mat-label>Search Stands</mat-label>
<button mat-icon-button matSuffix>
<mat-icon>search</mat-icon>
</button>
<input matInput type="text" (input)="onSearchTextChanged($event)" />
</mat-form-field>
The logic
export interface Filter {
query: string
groupBy: GroupBy
}
interface GroupBy {
field: string
value: string
}
@Component({
selector: 'app-searchbar',
templateUrl: './searchbar.component.html',
styleUrls: ['./searchbar.component.sass'],
})
export class SearchbarComponent implements OnInit {
@Output() searchTextChanged: EventEmitter<Filter> = new EventEmitter()
filter = {
query: '',
groupBy: { field: 'status', value: this.statusGroupBy },
}
constructor() {}
ngOnInit(): void {}
onSearchTextChanged(event) {
const { data } = event
const filter: Filter = {
...this.filter,
query: data,
}
this.searchTextChanged.emit(filter)
}
}
CodePudding user response:
If I got your question right you may use standard keyup
event handler to monitor which key user have pressed.
Component sample:
import { Component } from '@angular/core';
@Component({
selector: 'input-with-keyup-event',
template: `<mat-form-field appearance="fill">
<mat-label>Intput with KeyUp event handling</mat-label>
<input matInput type="text" [(ngModel)]="value" (keyup)="onKeyUp($event)" />
</mat-form-field>`
})
export class InputWithKeyUpEvent {
value = '';
onKeyUp(event: KeyboardEvent): void {
//Here you may put your logic. Now it's just console output:
console.log(event.key);
}
}
CodePudding user response:
If you notice the value from data
, it results in the current typing character.
If you want to get the whole value for the <input>
element, you need (event.target as HTMLInputElement).value
.
onSearchTextChanged(event) {
const { data } = event as InputEvent;
const filter: Filter = {
...this.filter,
query: (event.target as HTMLInputElement).value,
};
this.searchTextChanged.emit(filter);
}
And in the parent component, to get the string as the Character array:
get charArray(): string[] {
return Array.from(this.result?.query || []);
}