Adding formcontrol,formgrops and formarray to duplicated html angular

416 Views Asked by At

I am doing an add form for that I need the formcontrol,formgroup setup for all these values entered in the ts. Its normal stuff maybe. But here I have it very different. I have a add button which duplicates the set of forms in the html. I am finding it difficult to write formgroup logic and validators in the ts for it. Kindly help if u know(You can atleast tell me how to set up the formcontrol names ang bring it on to ts)

Note: Pls comment below if my question was unclear.

My stackblitz link : https://stackblitz.com/edit/angular-ivy-g8cty1?file=src%2Fapp%2Fapp.component.html

1

There are 1 best solutions below

3
On BEST ANSWER

You can declare your FormGroup like below.

myForm = new FormArray([]);
addRow() {
    const group = new FormGroup({
      firstName: new FormControl("", [Validators.required]),
      value: new FormControl("", [Validators.required])
    });
    this.myForm.push(group);
}

and invoke this function whenever user click on Add button. In Template to show the form. Loop through FormControl and bind it like below.

<div *ngFor="let form of myForm.controls;">
    <ng-container [formGroup]="form">
      <div>
        <label>Name</label
        ><input type="text" required formControlName="firstName" />
      </div>
      <span class="text-danger" *ngIf="isInValidFormControl(form,'firstName')">
        Name is required
      </span>
      <div>
        <label>Value</label><input type="text" formControlName="value" />
      </div>
    </ng-container>
</div>

Your validation with respect to total will be like below.

isValidTotal() {
    var values = this.myForm.controls.map((x) =>
      x ? Number(x.value.value) : 0
    );
    let sumTotal = values.reduce((a, b) => a + b);
    return sumTotal <= this.total;
}

And you can call this from template like this.

  <button (click)="addRow()" [disabled]="!isValidTotal()">Add</button>
  <button (click)="submit()" [disabled]="!isValidTotal()">Submit</button>
  <div *ngIf="!isValidTotal()">
    <p>{{errorMessage}}</p>
  </div>

Working sandbox

https://codesandbox.io/s/formarraydynamic-rqdhc?file=/src/app/app.component.html