Search code examples
angularangular-reactive-formsformarrayformgroups

How to use FormArray in angular


I creating form

createProduct = new FormGroup({
        name: new FormControl([''], Validators.required),
        category: new FormControl(),
        nomenclature: new FormControl(),
        descriptions: new FormControl(),
        models: new FormArray([
            new FormControl
        ])
    });

 get models() {
        return this.createProduct.controls['models'] as FormArray;
    }

and get an array of fields from the server.

 character(id = 1) {
        this.server.index('characteristic/?' + 'id=' + id).subscribe(response => {
            this.characters = response
        })
    }

Next, I want to build a form for the user,

 <div class="in-group mb-1" formArrayName="models">
                        <div *ngFor="let forms of models.controls">
                            <div *ngFor="let char of characters">
                                <label for="{{char.id}}">{{char.name}}</label>
                                <select class="form-control w-25" id="{{char.id}}" [formControlName]    =char.id>
                                    <option *ngFor="let val of char.value" value="{{val.id}}">{{val.value}}</option>
                                </select>
                            </div>
                        </div>
                    </div>

I can’t figure out how to properly name the fields for accepting answers, there can be as many fields as you like and grouped by condition

I don't know what to write here anymore...


Solution

  • The example you gave of your code was a little unclear to me. But I understood your general meaning of the problem you encountered.

    I made a simple example that can solve your problem

    //// section html

    <div [formGroup]="form">
      <div formArrayName="models">
        <div *ngFor="let item of form.get('models')['controls']; let i = index" [formGroupName]="i">
          <label for="{{item.value.id}}">{{item.value.name}}</label>
          <select class="form-control w-25" id="{{item.value.id}}" formControlName="dataSelect">
              <option *ngFor="let val of item.value.selectModel" value="{{val.id}}">{{val.value}}</option>
          </select>
        </div>
      </div>
    </div>
    
    <button (click)="testForm()">test</button>
    

    ////// section typescript

    constructor(private fb: FormBuilder) { }
    
      form: FormGroup;
      dataExampleModelsFormArray;
    
      ngOnInit(): void {
    
        this.form = new FormGroup({
          name: new FormControl([''], Validators.required),
          category: new FormControl(),
          nomenclature: new FormControl(),
          descriptions: new FormControl(),
          models: new FormArray([])
        });
    
        this.getData();
    
        this.dataExampleModelsFormArray.map(x => {
          (this.form.get('models') as FormArray).push(
            this.fb.group({
              id: x.id,
              name: x.name,
              selectModel: this.fb.array([...x.selectModel]),
              dataSelect: x.dataSelect
            })
          )
        })
      }
    
      getData() {
        this.dataExampleModelsFormArray = [
          {
            id: 1,
            name: 'label_1',
            selectModel: [
              { id: 1, value: 'select1_1' },
              { id: 2, value: 'select1_2' },
              { id: 3, value: 'select1_3' },
            ],
            dataSelect: ''
          },
          {
            id: 2,
            name: 'label_2',
            selectModel: [
              { id: 1, value: 'select2_1' },
              { id: 2, value: 'select2_2' },
              { id: 3, value: 'select2_3' },
            ],
            dataSelect: ''
          },
          {
            id: 3,
            name: 'label_3',
            selectModel: [
              { id: 1, value: 'select3_1' },
              { id: 2, value: 'select3_2' },
              { id: 3, value: 'select3_3' },
            ],
            dataSelect: ''
          }
        ]
      }
    
    testForm() {
        console.log(this.form.value);
      }
    

    Here, when the select boxes are filled. Their value is stored in the dataSelect key.

    This is how you can have a completely dynamic form that has inputs like select inside that form.