Hi guys i'm trying to build a rective form, which has a formArray and i want to be able to add or remove input fields dynamically but i get the error: Cannot find control with unspecified name attribute
here's my code:
the ts file:
@Component({
selector: 'app-create-ilm-policy',
templateUrl: './create-ilm-policy.component.html',
styleUrls: ['./create-ilm-policy.component.scss']
})
export class CreateIlmPolicyComponent implements OnInit {
mainForm:FormGroup
constructor(){}
get patterns(){
return <FormArray>this.mainForm.get('indexPatterns')
}
ngOnInit(): void {
this.mainForm = new FormGroup({
indexPatterns: new FormArray([this.addIndexPattern()]),
rolloverAlias: new FormControl()
})
}
addIndexPattern(): FormControl{
return new FormControl()
}
removeIndexPatternRow(index: number) {
(<FormArray>this.mainForm.get('indexPatterns')).removeAt(index)
}
addIndexPatternRow(){
(<FormArray>this.mainForm.get('indexPatterns')).push(this.addIndexPattern())
}
}
the html file:
<form [formGroup]="mainForm">
<div formArrayName="indexPatterns" *ngFor="let pattern of patterns.controls; index as i">
<div class="d-flex align-items-center" [formControl]="i">
<mat-form-field appearance="fill">
<mat-label>modèle d'indices</mat-label>
<input matInput [formControl]="patterns.controls[i]"> <!--line that throws the error!!!!!!!-->
<mat-hint>ajouter * à la fin</mat-hint>
</mat-form-field>
<mat-icon class="pointer" color="warn" (click)="removeIndexPatternRow(i)" svgIcon="delete_forever" aria-hidden="false"></mat-icon>
</div>
</div>
</form>
[formGroup]we pass the[formControlName]instead of actual controls and we let angular pick the control itself.