HTML:
<form [formGroup]="basicForm">
<section>
<mat-form-field>
<mat-label>Select Country*</mat-label>
<input matInput type="text" maxlength="20" formControlName="country [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="countryDisplayWith">
<mat-option *ngFor="let country of filteredCountryAutoCompleteOptions | async [value]="country">
{{country}}</mat-option>
</mat-autocomplete>
</mat-form-field>
</section>
</form>
/////////////////////////////////////////////////
TS:
filteredCountry: string[] = ['abc', 'def', 'ghi'];
this.basicForm = new FormGroup({
country: new FormControl({ value: '' }, Validators.required) });
filteredCountryAutoCompleteOptions: Observable<string[]> | undefined;
countryDynamicFilter() {
this.filteredCountryAutoCompleteOptions = this.basicForm.controls.country.valueChanges.pipe(
startWith(''),
map((value) => this._filter(value))
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.filteredCountry.filter(
(option) =>
option.toLowerCase().includes(filterValue)
);
}
countryDisplayWith(op: any) {
return op ? op: '';
}
I am getting [Object Object] initially in Input Box as a value, But autocomplete works fine.
I believe this is something to do with [displayWith]. need help to figure this out..
CodePudding user response:
.component.html
Modify the <mat-option>
element to display string for example {{country.name}}
instead of {{country}}
as country
is an object.
<mat-autocomplete #auto="matAutocomplete" [displayWith]="countryDisplayWith">
<mat-option *ngFor="let country of filteredCountryAutoCompleteOptions | async" [value]="country">
{{ country.name }}
</mat-option>
</mat-autocomplete>
And altering the function for [displayWith]
to display the country.name
instead of country
.
.component.ts
countryDisplayWith(op: any) {
return op ? op.name : '';
}