3

I'm having some trouble getting form fields to populate from an array. My original thinking is to input the array from individual components to a single component that will handle the form. Instead of making multiple forms. But I can't seem to get it to work. Any help would be appreciated! I've been through Google/stack/medium and can't seem to find anything. I've done an example on plunkr.

https://stackblitz.com/edit/angular-t7hcq6

In the ts file:

  public demoForm: FormGroup;
  public arrayItems: data = [];

  private formFields = ["Sku", "Title"];

  constructor(private _formBuilder: FormBuilder) {
    this.demoForm = this._formBuilder.group({
      demoArray: this._formBuilder.array([])
    });
  }

  ngOnInit() {
    this.formFields.map(field => {
      this.arrayItems.push({ title: field });
      this.demoArray.push(this._formBuilder.control(''));
    });
  }

  get demoArray() {
    return this.demoForm.get("demoArray") as FormArray;
  }

In the template:

<form [formGroup]="demoForm">
   <div formArrayName="demoArray" 
      *ngFor="let arrayItem of arrayItems; let i=index">
      <input type="checkbox"[formControl]="demoArray[i]">
      <label>{{arrayItem.title}}</label>
   </div>
</form>

Thank you guys.

2
  • It's generally a good idea to provide some code here on your question to help us answer. Are you using FormArray? Commented Oct 17, 2019 at 16:47
  • Sorry @WillAlexander This is my first time contributing to Stack I wasn't aware. The problem has now been resolved however below. Thanks for taking the time though. Commented Oct 17, 2019 at 17:45

1 Answer 1

3

change your template like so:

<form [formGroup]="demoForm">
   <div formArrayName="demoArray" 
      *ngFor="let arrayItem of arrayItems; let i=index">
      <input type="checkbox" [formControlName]="i"> <!-- this line -->
      <label>{{arrayItem.title}}</label>
   </div>
</form>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much for your help on this. I appreciate your support!
How to add a new checkbox using this example?
@RafaelGuimarães this.demoArray.push(this._formBuilder.control(/* your new control stuff */));

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.