我正在使用带有自动完成功能的反应式表单 . 我在我的应用程序的其他部分使用了自动完成功能但我无法弄明白 . 我有一个formarray,每当我想在我的case中添加一个新的传感器时添加一个输入.autocomplete works在我的第一次输入中很好但是当我尝试添加更多输入时会显示错误: Error: Must supply a value for form control at index: 1
HTML:
<div class="row">
<div class="input-field col s10">
<div class="form-group">
<div formArrayName="sensors_id">
<div *ngFor="let sensor of addHomeboxPForm.get('sensors_id')['controls']; let i = index">
<br>
<input formControlName="{{i}}" type="text" placeholder="Select Sensor" aria-label="Number" matInput [matAutocomplete]="auto1">
<mat-autocomplete autoActiveFirstOption #auto1="matAutocomplete" [displayWith]="displayWith" >
<mat-option (onSelectionChange)="updateForm($event, [sensor.sensors_id], 'sensors_id')" *ngFor="let sensor of filteredOptionsS | async" [value]="sensor.sensor_serial">
{{sensor.sensor_serial}}
</mat-option>
</mat-autocomplete>
<div class="button-left">
<button *ngIf="addHomeboxPForm.controls.sensors_id.value.length > 1" type="button" class="fa" (click)="onRemoveItem(i)">RemoveSensor</button>
</div>
</div>
</div>
</div>
<div class="input-field col s2">
<button type="button" class="btn" (click)="onAddItem()">AddSensor</button>
</div>
TS:
formarray: 'sensors_id': this.fb.array([], Validators.required),
updateForm(ev: any, idd: any, componentid: any) {
if (ev.isUserInput) {
if (componentid === 'sensors_id') {
this.sensorId = idd;
this.addHomeboxPForm['controls']['sensors_id'].setValue([ev.source.value])
}
}
}
onAddItem() {
(<FormArray>this.addHomeboxPForm.controls['sensors_id']).push(new FormControl('', Validators.required));
}
onRemoveItem(index: number) {
(<FormArray>this.addHomeboxPForm.controls['sensors_id']).removeAt(index);
}
我是新来的,所以我很抱歉,如果我不是那么清楚..但我还没有找到解决方案
1 回答
在模板html中使用fortmcontrolName之前,应该在组件中定义fortmcontrolName .
我看到你使用的
<input formControlName="{{i}}"
无效,因为Angular无法找到最初声明被动形式的formControl / field .你可以阅读更多关于reactive forms here:的信息
希望能帮助到你 .