Ald*_*azi 6 angular angular-reactive-forms formarray mat-autocomplete
我正在使用带有 mat 自动完成功能的反应式表单。我在应用程序的其他部分使用了自动完成功能,但我无法弄清楚。我有一个formarray,每次我想在我的情况下添加一个新传感器时都会添加一个输入。自动完成在我的第一个输入中工作正常,但是当我尝试添加更多输入时显示错误:错误:必须在索引处为表单控件提供一个值: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>
Run Code Online (Sandbox Code Playgroud)
TS:
格式数组: '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);
}
Run Code Online (Sandbox Code Playgroud)
我是新手,所以如果我不是很清楚,我很抱歉......但我还没有找到解决方案
在模板 html 中使用 fortmcontrolName 之前,应该在组件中定义它。
我看到您使用了<input formControlName="{{i}}"无效的方法,因为 Angular 无法找到最初声明反应表单的 formControl/字段。
在组件类中创建控件后,必须将其与模板中的表单控件元素关联。使用 ReactiveFormsModule 中包含的 FormControlDirective 提供的 formControl 绑定来更新表单控件的模板。
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
3333 次 |
| 最近记录: |