1
votes

I am a newbie to Angular 6.

Here's html markup for the forms in which I am facing some problems

<form [formGroup]="detailsForm">
    <div class="row parent-row" *ngFor="let row of formData;">
        <input class="input-lg parent-input-primary" placeholder="{{row.first }} formControlName ={{row.first}}" />
        <input class="input-lg parent-input-secondary" placeholder="{{row.second }} formControlName ={{row.second}}" />
    </div>
</form>

where formData is a Json object of type:

formData: any[] = [
    {
        first: 'business-name',
        second: 'business-type',

    },
    {
        first: 'contact-mobile',
        second: 'purpose',
    }
]

here first and second are dynamic strings and are unique throughout the form. I need to initialize the form using angular reactive forms Module something like this :

    detaislForm = FormGroup;
    this.detailsForm = new FormGroup({
        //here I need to write something to init FormControl here, so that angular knows formControls by first and second variables of FormData 
     }
    );

Can you suggest me a way to insert formcontrols in formGroup by this method?

1

1 Answers

2
votes

Using Form Array Here:

Reference ---> https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays

STACKBLITZ DEMO

TS:

formData: any[] = [
    {
      first: 'business-name',
      second: 'business-type',

    },
    {
      first: 'contact-mobile',
      second: 'purpose',
    }
  ]
  detailsForm: FormGroup;

  constructor(private _fb: FormBuilder) {

  }
  ngOnInit() {

    this.detailsForm = this._fb.group({
      formData: this._fb.array([])
    });

    for (let data of this.formData) {
      this.addValue(data);
    }
  }
  createFormArray(data) {
    return this._fb.group({
      first: data.first,
      second: data.second
    })
  }

  addValue(data) {
    this.getData().push(this.createFormArray(data));
  }
  getData() {
    return this.detailsForm.controls.formData as FormArray
  }

HTML:

<form [formGroup]="detailsForm">
    <div formArrayName="formData">
        <div *ngFor="let row of detailsForm.get('formData').controls; let i = index;" [formGroupName]="i">
            <input class="input-lg parent-input-primary" placeholder="first" formControlName="first" />
            <input class="input-lg parent-input-secondary" placeholder="second" formControlName="second" />
        </div>
    </div>
</form>