0

I am trying to wrap my head around the best way to use Angular 4 FormGroup and FormBuilder. I have some dummy json data that I am working with for now such as this:

bins = [ 
 {
   id: '101-Test',
   system: 'test-system',
   shape: 'round'
 },
   id: '102-Test',
   system: 'test-system',
   shape: 'round'
]

What I intend to do is have a UI that will show rows of 'bins' which can be edited but also the ability to add a new bin. So the html/ngFor/ngIf's would look like this:

<div id="bins">
   <div class=bin-card new" *ngIf="addBinCardVisible">
      <form [formGroup]="binSetupForm">
          <label>Bin # <input type="text" formControlName="id"></label>
          <label>Bin # <input type="text" formControlName="system"></label>
          <label>Bin # <input type="text" formControlName="shape"></label>
      </form>
   </div>
   <div class="bin-card-wrap" *ngFor="let bin of bins; let i = index">
      <form [formGroup]="binSetupForm">
         <label>Bin # <input type="text" formControlName="id"></label>
          <label>Bin # <input type="text" formControlName="system"></label>
          <label>Bin # <input type="text" formControlName="shape"></label>
      </form>
   </div>
</div>

And then in my Typescript I would have something along the lines of:

export class BinSetupComponent implements OnInit {

   addBinCardVisible = false;

   binSetupForm: FormGroup;

   constructor(private formBuilder: FormBuilder) { }

   ngOnInit() {
      this.buildForm();
   }

   buildForm(): void {
     this.binSetupForm = this.formBuilder.group({
        id: '',
        system: '',
        shape: ''
     });
   }

   addNewBin() {
      this.bins.splice(0, 0, this.binSetupForm.value);
      this.addBinCardVisible = false;
      this.binSetupForm.reset();
   }  
}

As you can see I am using Angular Form Builder to build the values of the binSetupForm and then pushing the new form value into my dummy array of data. How do I also use this Form Group/Controls to set the values of the edit forms in the *ngFor. Should I somehow be implementing patchValue from Angular and if so how? Missing the link on how to use these form controls for all instances of this form. Any help is much appreciated.

1 Answer 1

1

What you would be looking to use is FormArray and you will setup your form like so

this.binsForm = new FormGroup({
    bins: new FormArray([
        new FormGroup({
            id: new FormControl('101-Test'),
            system: new FormControl('test-system'),
            shape: new FormControl('round')
        }),
        new FormGroup({
            id: new FormControl('102-Test'),
            system: new FormControl('test-system'),
            shape: new FormControl('round')
        })
    ]
});

In your *.component.html file

<div [formGroup]="binsForm">
    <div formArrayName="bins">
      <div *ngFor="let bin of bins; let i = index">
        <div [formGroupName]="i">
            <input type="text" formControlName="id" />
            <input type="text" formControlName="system" />
            <input type="text" formControlName="shape" />
        </div>
      </div>
    </div>
</div>

Here is a link to a full example setup

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

6 Comments

Thanks for the response, I will have about 500 entries in my actual data, so how to set those controls based on the data rather than passing the data in each time?
Have you had a look at the full example link
Thank, man. Only question is why is the addBin() function only pushing an empty object to the bins array rather than storing the value from the form group instance?
addBin creates a new bin and pushes it to the array, if you want to save the updated array just call this.binsForm.value, I have updated the code in the link to show you. I passed an empty object because createBin function checks each property like so bin.id || ''.
@than Looks nice. I want to ask one question: Let's say customer removes the input data in any field and clicks save. How to display the error to show them that they must fill empty forms with some pattern.validations?
|

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.