Issue
I have a little problem, I want to create a form using Angular :
here is my HTML :
<form [formGroup]="requeteForm" (ngSubmit)="ajouter()" *ngIf=" tables!= null">
<div class="form-group" *ngFor="let col of colonne; let i=index">
<label for="{{col}}">{{col}}</label>
<input type="text" class="form-control" id="{{col}}" formControlName="{{col}}">
</div>
</form>
As you can see the formControlName take a variable, the problem is how can I get the variable to init the formGroup ?
For exemple :
this.requeteForm = this.formBuilder.group(
{
{{col}}: ['', Validators.required], //It's just an exemple about what I want to do
}
);
UPDATE
I want to bring in some more information :
I fact what I want to do is to create a form to add parameters in my dataBase the thing is I get all the columns’s name in an Array so I have colonne[nom, number] that are the name of my colums.
The problem is that they don’t have a "title" like {id : 1, name : ‘Tom’} so I the formBuilder I can’t use nom and number since it will change is the table change… I have tried using a for in this.colonne but the syntaxe is wrong for the formBuilder TT Another problem is how to get the information of the input since I won’t be able to call them using particular name…
Hope you can help me ^^ Thank you
Solution
You have to use FormArray
which contains FormControl
.
Try like this :
requestForm: FormGroup;
colonne = [
{ id: 1, name: "Name 1" },
{ id: 2, name: "Name 2" },
{ id: 3, name: "Name 3" },
{ id: 4, name: "Name 4" },
];
get cols() {
return this.requestForm.get("cols") as FormArray;
}
constructor(private formBuilder: FormBuilder) {
this.requestForm = this.formBuilder.group({
cols: new FormArray(this.colonne.map(col => new FormGroup({
item: new FormControl(col.name)
})))
});
}
ajouter() {
}
Then in your HTML
<form [formGroup]="requestForm" (ngSubmit)="ajouter()">
<ng-container formArrayName="cols">
<div *ngFor="let col of cols.controls; index as i">
<ng-container [formGroupName]="i">
<input formControlName="item" />
</ng-container>
</div>
</ng-container>
</form>
This code is not tested so maybe you will have to adjust. You have a whole example here : https://netbasal.com/angular-reactive-forms-the-ultimate-guide-to-formarray-3adbe6b0b61a
UPDATE
I’ve made a working StackBlitz (without ajouter()
function) here : https://stackblitz.com/edit/angular-ivy-wympwa?file=src/app/app.component.ts