Mat-Autocomplete formControlName [英] Mat-Autocomplete formControlName
本文介绍了Mat-Autocomplete formControlName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Mat-Autocomplete 上使用 formControlName 时遇到问题.我不知道为什么,但我的 formControlName 不会发送数据,是我写错了吗?当我尝试从 HTML 中删除 [formControl] 时,它总是无法过滤.
I have issue using formControlName on Mat-Autocomplete. i dont know why but my formControlName wont send the data, am i put it wrong? When i try to remove [formControl] from HTML, its always cant filter.
HTML
<form [formGroup]="form" #legalDataFrm="ngForm" autocomplete="off" fxLayout.gt-sm="column" fxFlex="1 1 auto" novalidate>
<input type="text" placeholder="Pilih Bank"
formControlName="bankName" matInput
[formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete
#auto="matAutocomplete"
(optionSelected)='onChangeBank()'
[displayWith]="displayFn">
<mat-option>Pilih Bank</mat-option>
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.bankName}}
</mat-option>
</mat-autocomplete>
</form>
TS_bankService 是我获取银行列表的地方,_validationService 是我获取每个表单名称验证的地方.
TS _bankService is where i get the Bank List, _validationService is where i get the validation for each form name.
export class FpLegalDataFormComponent implements OnInit, OnDestroy {
form: FormGroup;
myControl = new FormControl();
options: User[];
filteredOptions: Observable<User[]>;
constructor(
private activatedRoute: ActivatedRoute,
private formBuilder: FormBuilder,
public _validationsService: ValidationsService,
public _bankService: BankService
) {
}
this.form = this.formBuilder.group({
bankName : [bankName, Validators.required]
});
displayFn(user?: User): string | undefined {
return user ? user.bankName : undefined;
}
private _filter(name: string): User[] {
const filterValue = name.toLowerCase();
return this.options.filter(option =>
option.bankName.toLowerCase().indexOf(filterValue) > -1);
}
private initDropdown() {
this._bankService.getBank().then((response) => {
console.log(response.data.bankList)
this.options = response.data.bankList;
console.log(this.options)
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith<string | User>(''),
map(value => typeof value === 'string' ? value : value.bankName),
map(name => name ? this._filter(name) : this.options.slice())
);
})
}
推荐答案
首先这样初始化表单控件就好了:
First of all it's good to initialize the form control so insted of:
this.form = this.formBuilder.group({
bankName : [bankName, Validators.required]
});
使用
this.form = this.formBuilder.group({
bankName: new FormControl(bankName, Validators.required)
});
并解决问题
<input type="text" placeholder="Pilih Bank"
formControlName="bankName" matInput
[formControl]="myControl" [matAutocomplete]="auto">
使用
<input type="text" placeholder="Pilih Bank" matInput
[formControl]="form.get('bankName')" [matAutocomplete]="auto">
它应该可以解决您的问题.
it should fix your problem.
这篇关于Mat-Autocomplete formControlName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文