I need to implement an auto-complete feature for the county
field due to a large number of items in the list causing inconvenience to users who have to scroll extensively. Currently, there are two issues with the code.
The first problem is that although the input box looks fine, it does not filter the list based on user input.
The second issue is related to my county
object having two properties - countyId
and countyName
. When a county is selected from the list, it displays the countyId
instead of the name, as it is bound to the id. How can I modify it to display the name while still being bound to the id for server communication?
Below is the HTML code snippet:
<mat-form-field appearance="outline" fxFlex="50" class="pr-4">
<input type="text" placeholder="Select County" name="" matInput [formControl]="countyId" [matAutocomplete]="auto">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let county of counties" [value]="county.countyId">
{{county.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
And here is the corresponding TypeScript file code:
window.matchMedia('<br />');
newCustomerForm: FormGroup;
counties; // List of counties
subCounties;
filteredCounties: Observable<string[]>;
this.newCustomerForm = this._formBuilder.group({
nationalId: ['', Validators.required],
name: ['', Validators.required],
gender: ['', Validators.required],
phone1: [''],
phone2: [''],
countyId: ['', Validators.required],
subCountyId: ['', Validators.required],
bishopName: ['', Validators.required],
bishopPhone: ['', Validators.required],
address: ['', Validators.required],
additionalInfo: [''],
input1: [''],
input2: [''],
defaultingRecord: [''],
});
ngOnInit() {
// Retrieving the list of counties
this.countyService.getCounties().subscribe((response) => {
this.counties = response;
this.filteredCounties = this.newCustomerForm.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
});
// Retrieving the list of sub-counties
this.subCountyService.getSubCounties().subscribe((response) => {
this.subCounties = response;
});
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.counties.filter(county=> county.name.toLowerCase().indexOf(filterValue) === 0);
}
Additional context provided through an image: https://i.sstatic.net/wi0v5.jpg