【发布时间】:2019-04-02 08:11:54
【问题描述】:
我需要实现一个简单的自动完成文本框,允许从按名称过滤和显示的对象列表中进行选择。
例如,我有一组 Country 对象,它们具有某些属性(countryName、countryCode、countryId.. 等等),我想按 countryName 在文本框中显示和过滤,但是一旦用户选择了国家,我就想要整个对象被选中。
我可以用[(ngModel)] 或FormControl 解决这个问题,但现在我必须使用FormGroup 并且我不知道如何使用属性formControlName="..."
这里是 sn-p 示例:
.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;
}
}
}
是否有任何解决方案可以使用自动完成文本框/选择来过滤对象列表并将所选元素绑定到 FormGroup 元素?
【问题讨论】:
-
我认为你应该删除 [displayWith]="displayFn" 并参考这个link
-
我已经尝试遵循 Angular 的文档,但它只解决了 [formControl] 的问题,而不是整个表单组的问题...我的意思是有一个 formControName="..." 的示例,但不能不要将它应用于我的问题...我必须管理整个对象,而不仅仅是文档中的单个字符串
标签: angular autocomplete angular-material