0

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

4
  • Don't I need to have a different one for each col ? So that I can get later using : const formValue = this.requeteForm.value; let element = { selectCol: formValue.selectCol, } Commented Apr 15, 2021 at 14:34
  • In fact I have an array named colonne which contain : (nom, nombre) I want to input for nom and nombre, but colonne depend on what I have in my dataBase that's why I need to use variable Commented Apr 15, 2021 at 14:39
  • yeah, it's defined, sorry, my bad, you need to use formArray Commented Apr 15, 2021 at 14:41
  • No problem, thank you ^^ Commented Apr 15, 2021 at 14:43

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you ^^ If I have understand the get cols create an array with everything in the form is that right ?
@snsdtiti I've updated my code and give you a working example. Please check and tell me if it's working. The get allow you to access your FormArray. You need it to display each item into the HTML.
It's working better, I now have the input with the name inside ^^ But i have some errors I don't really know how to repair : Cannot read property 'get' of undefined for the line return this.requeteForm.get('cols') as FormArray; And how can I get the result of the input ?
And I forgot but I have also this error : formGroup expects a FormGroup instance. Please pass one in But your code seem right...
Be careful to the imports. Make sure you imported FormsModule and ReactiveFormsModule in you .module.ts. For the first error, add a ? like this this.requestForm?.get('...') as FormArray
|
0

You can use a FormArray or a FormGroup. You choice one or another according the data you need.

//If you create a FormGroup is because you need a data like
{
   name1:"Peter"
   surname:"Smith"
}
//If you create a FormArray of FormControls is because you need a data like
[
   "Peter","John"
]
//If you create a FormArray of FormGroup is because you need a data like
[
   {name:"Peter",surname:"Smith"},
   {name:"John",surname:"Jhon"}
]

If we want create a FormGroup according an array of columns you need create a FormGroup empty and use addControl, e.g.

const columns=["name","surname"]
const form=new FormGroup({})  //create an empty formGroup
columns.forEach(x=>{
   form.addControl(x,new FormControl()) //add a FormControl to the formGroup
})

Note:recently @Raru ask about a dynamic form builder in this SO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.