I am using Reactive forms with mat autocomplete. I used autocomplete in other parts of my app but i can't figure this out. I have a formarray which adds an input every time I want to add a new sensor in my case. autocomplete works fine in my first input but when I try to add more inputs an error is shown : 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);
}
I am new to this so i am sorry if i am not that clear..but i havent found a solution yet