Angular FormGroup中筛选更多选项的自动完成输入
我需要实现一个简单的自动完成文本框,允许从按名称过滤和显示的对象列表中进行选择 例如,我有一个具有某些属性(countryName、countryCode、countryId..等等)的Country对象数组,我希望在文本框中按countryName显示和筛选,但一旦用户选择了国家,我希望整个对象都被选中 我可以用Angular FormGroup中筛选更多选项的自动完成输入,angular,autocomplete,angular-material,Angular,Autocomplete,Angular Material,我需要实现一个简单的自动完成文本框,允许从按名称过滤和显示的对象列表中进行选择 例如,我有一个具有某些属性(countryName、countryCode、countryId..等等)的Country对象数组,我希望在文本框中按countryName显示和筛选,但一旦用户选择了国家,我希望整个对象都被选中 我可以用[(ngModel)]或FormControl解决这个问题,但现在我必须使用FormGroup,我不知道如何使用属性formControlName=“…” 以下是代码片段示例: .ht
[(ngModel)]
或FormControl
解决这个问题,但现在我必须使用FormGroup
,我不知道如何使用属性formControlName=“…”
以下是代码片段示例:
.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>
是否有任何解决方案可以使用自动完成文本框/选择来过滤对象列表,并将所选元素绑定到FormGroup
元素?编辑:
好的,我把它和自动完成一起使用。这是我的密码:
HTML:
施工前:
public formGroup;
countries: Country[] = [{"name": 'Greece', "id": "1"}, {"name": 'Italy', "id": "2"}, {"name": 'Spain', "id": "3"}]
filteredCountries: Observable<Country[]>;
constructor(public formBuilder: FormBuilder)
this.formGroup = this.formBuilder.group({
country: ['', Validators.required]});
建造师之后:
public formGroup;
countries: Country[] = [{"name": 'Greece', "id": "1"}, {"name": 'Italy', "id": "2"}, {"name": 'Spain', "id": "3"}]
filteredCountries: Observable<Country[]>;
constructor(public formBuilder: FormBuilder)
this.formGroup = this.formBuilder.group({
country: ['', Validators.required]});
关于恩戈尼特:
this.filteredCountries = this.formGroup.get('country').valueChanges
.pipe(
startWith<string | Country>(''),
map(value => typeof value === 'string' ? value : (<any>value).name),
map(name => name ? this._filter(name) : this.countries.slice())
);
我使用材料文档使其工作,并将其添加到我的现有项目中。如果你发现任何地区的参考,而不是它的国家,因为这是我的项目中的关键字,我提前道歉。这将使该值取整个对象。您可以测试并打印console.log(this.formGroup.value)代码>
onSubmit.我认为您应该删除[displayWith]=“displayFn”并参考此内容。我已经尝试按照angular的文档进行操作,但它只解决了[formControl]的问题,而不是整个FormGroup的问题。。。我的意思是有一个formControName=“…”的例子,但无法将其应用于我的问题。。。我必须管理整个对象,而不仅仅是文档中的单个字符串。我已经尝试过这个解决方案,不幸的是没有任何改变。。但无论如何,这是以简化的方式定义表单组的正确方法。您可以尝试mat select而不是auto complete。它确实适用于我以前使用过的对象。然后,您可以使用一个输入,使用javascript通过*ngFor=“let country of filteredCountries | async”来过滤select选项,如autoComplete documentation()。我会亲自尝试,很快会回来找你。好的,如果你需要更多信息,请告诉我。我也尝试了mat select,但它似乎不支持我需要的那种自动完成。。。它只是在键入时将焦点移到列表中的元素上,但我需要对该列表进行强大的筛选检查我的编辑,并告诉我是否还有其他需要排序的内容它似乎工作得很好,至少我有一个起点!非常感谢你!
displayFn(country?: Country): string | undefined {
return country ? country.name : undefined;
}
private _filter(name): Country[] {
const filterValue = name.toLowerCase();
return this.countries.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
}