材质自动完成在动态添加 MatInput 字段后不起作用,但在添加之前它起作用并填充



该代码适用于第一个默认matInput字段,并在输入更改期间填充建议列表,但是当我向表单添加新字段时,建议列表不起作用,并在输入更改期间停止。

<form
[formGroup]="feasibilityForm"
(ngSubmit)="onSubmit(feasibilityForm.value)"
>
<mat-form-field
[style.width.%]="100"
formArrayName="serviceNames"
*ngFor="let service of serviceNames.controls; let i = index"
>
<mat-label> Service Activity </mat-label>
<input
[formControlName]="i"
matInput
type="text"
[matAutocomplete]="auto"
/>
<mat-autocomplete #auto="matAutocomplete">
<mat-option
*ngFor="let item of filteredOptions"
[value]="item.Service"
>
{{ item.Service }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<div class="form-element">
<button mat-flat-button color="primary" type="submit">Primary</button>
</div>
</form>

目的是动态地将matInput字段添加到表单中,并为添加的每个matInput字段自动完成建议列表。

options = [];
feasibilityForm;
filteredOptions;
title = 'my-app';
constructor(private service: MyService, private formBuilder: FormBuilder) {
}
ngOnInit() {
this.initForm();
this.getNames();
this.service.getLocalData().subscribe(data => {
console.log(data)
})
}
initForm() {
this.feasibilityForm = this.formBuilder.group({
serviceNames: this.formBuilder.array([this.formBuilder.control('')]),
})
this.feasibilityForm.get('serviceNames').valueChanges.subscribe((response: any) => {
console.log('data is ', response);
this.filterData(response);
})
}
get serviceNames() {
return this.feasibilityForm.get('serviceNames') as FormArray;
}
addServiceName() {
this.serviceNames.push(this.formBuilder.control(''));
this.getNames();
this.filteredOptions = [];
}
onSubmit(value) {
console.log(this.serviceNames.value)
}
filterData(enteredData) {
this.filteredOptions = this.options.filter((item) => {
console.log(item.Service)
return item.Service.toString().toLowerCase().indexOf(enteredData.toString().toLowerCase()) > -1
})
}
getNames() {
this.service.getLocalData().subscribe((response: any) => {
this.options = response;
this.filteredOptions = response;
})
}

所以问题是来自你的filterData。您循环遍历选项而不是enteredData

原因是enteredData将成为一个数组,当你添加更多的输入。

让我们看一个小例子:options = ['1','2','3']

  1. 1输入:enteredData = [1] =>toString返回'1'。options.indexOf('1')返回true。
  2. 现在你增加了一个输入=>enteredData =['1','1'](假设您在两个输入框中都输入了文本)=>toString返回'1,1' =>options.indexOf('1,1')总是返回-1。

最新更新