I need your help. I'm working with reactive forms and using matautocomplete
to search for elements. I subscribe to changes in my input
to search for my items. The fact is that I need to insert a certain value into my input
using patchValue
. I try to do it in several ways, but it doesn't work. What am I doing wrong? Thank you very much
HTML
<input [matAutocomplete]="auto" matInput
formControlName="targetListValue"
(input)="inputFilterValue()">
<mat-autocomplete
#auto="matAutocomplete"
[displayWith]="displayFn"
<mat-option *ngFor="let targetItem of filteredTargetListOptions"
[value]="targetItem">
{{targetItem.name}}
</mat-option>
</mat-autocomplete>
TS
ngOnInit(): void {
this.form = new FormGroup({
targetListValue: new FormControl(null, [Validators.required]),
});
inputFilterValue() {
this.form.controls.targetListValue.valueChanges.subscribe((inputValue) => {
this.filteredTargetListOptions = this.filteredTargetListOptions.filter(element => element.name.toLowerCase().includes(inputValue) || element.name.includes(inputValue));
})
}
displayFn(option?: ITargetData): string | undefined {
return option ? option.name : undefined;
}
// First way
setTimeout(() => {
this.form.patchValue({ targetListValue: 'Hello' })
},0)
// Second way
this.form.controls.targetListValue.patchValue('Hello');