I need to implement a simple autocomplete textbox that allow to choose from list of objects filtered and displayed by name.
For example i have a array of Country objects that have some property (countryName, countryCode, countryId.. so on), i want to display and filter in the textbox by countryName but once user select the country i want that whole object gets selected.
I could solve this problem with [(ngModel)] or FormControl but now i have to use FormGroup and i can't figure out how to use property formControlName="..."
here's snippet example:
.html
<form [formGroup]="formGroup">
[...]
<mat-form-field>
<input type="text" placeholder="{{'BIRTH_COUNTRY'|translate}}" matInput formControlName="birthCountry"
[matAutocomplete]="auto" required>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let country of countries" [value]="country">
{{country.CountryName}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
.ts
export class PersonalDataComponent implements OnInit {
public formGroup: FormGroup;
countries?: Country[];
constructor(public service: RegisterService) {
this.formGroup = new FormGroup({
name: new FormControl(null, Validators.required),
lastName: new FormControl(null, Validators.required),
gender: new FormControl(null, Validators.required),
birthDate: new FormControl(null, Validators.compose([Validators.required, legalAgeValidator])),
birthCountry: new FormControl(null, Validators.required),
});
displayFn(country ?: Country): string | undefined {
return country ? country.CountryName : undefined;
}
}
}
is there any solution to use a autocomplete textbox/select to filter object list and bind the selected element to a FormGroup element?