Pratyush
Pratyush

Reputation: 183

Angular: Multiple Select Using FormGroup and FormArray

How could I create a multiple select type element which would push an object to a formarray on being clicked?

I want the final JSON object to look like this:

{
    business_id: [ {
                      name: "one"

                    },]
}

Here is my .ts file

 businesses = [
    {name: "one", id: 0},
    {name: "two", id: 1}
  ]

 ngOnInit(): void {
    this.leadGenerateForm = new FormGroup({
      'business_id': new FormArray([])
    })
  }

onClickBusiness(){
    const group = new FormGroup({
      'name': new FormControl(null)
    });
    (<FormArray>this.leadGenerateForm.get('business_id')).push(group);
  };

Here is the HTML template

 <form formGroupName="leadGenerateForm">
        <div formArrayName="business_id">
            <select multiple (click)="onClickBusiness()">
                <div *ngFor="let businessControl of leadGenerateForm.get('business_id')['controls']; let i=index">
                    <options [formControlName]="i">{{businessControl.name}}</options>
                </div>
            </select>
        </div>
    </form>

Upvotes: 0

Views: 5885

Answers (1)

SELA
SELA

Reputation: 6878

I assume you need to add multiple select options in controller upon the select controllers value has been selected.

I have added a simple solution and its working demo here.

In HTML :

<form [formGroup]="form" (ngSubmit)="submit()">
    <p>Select a value </p>
    <div formArrayName="items" *ngFor="let item of form.controls['items'].controls; let i = index">
        <div [formGroupName]="i">
            <select  formControlName='name' >
                    <option *ngFor="let opt of businesses; let i =index" [value]="opt.name">{{opt.name}}</option>         
            </select>
        </div>
    </div>
</form>

Component.ts :

import { Component, OnInit } from "@angular/core";
import { FormGroup, FormArray, FormBuilder } from "@angular/forms";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  name = "Angular 6";
  form: FormGroup;
  businesses = [{ name: "one", id: 0 }, { name: "two", id: 1 }];
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      items: this.fb.array([this.createItem()])
    });
    this.onChanges();
  }

  createItem() {
    return this.fb.group({
      name: ["Jon"]
    });
  }

  onChanges(): void {
    this.form.get("items").valueChanges.subscribe(value => {
      this.businesses.push({
        name: value[0].name,
        id: Math.floor(Math.random() * 100 + 1)
      });
    });
  }
}

Upvotes: 1

Related Questions