sandeep v
sandeep v

Reputation: 43

how to add form control group dynamically in angular

I am new to angular and I am adding some field using form controls based on my requirements. I need to add a few fields dynamically which contains an array. But I don't know how to show the user that kind of functionality in the UI. Kindly help to achieve that. Here is the sample JSON

{
  "city": "hyderabad",
  "comboDesciption": "ioioioyio",
  "label": "combo", 
  "price": 650,
  "productIds": "Mutton Liver,Chicken",
  "qtyIds": "500gm,700gm"
}

In the above JSON, I have productIds where I need to pick multiple products for a combo and their respective quantity weights are referred to in the qtyIds. Kindly suggest me how to add my form control group in array to achieve this

Upvotes: 0

Views: 2075

Answers (1)

ionut-t
ionut-t

Reputation: 1177

I'm not sure if I understood you correctly.

Here is how you can use reactive forms in your case:

myForm: FormGroup;

constructor(private fb: FormBuilder) {}

ngOnInit(): void {
 this.myForm = this.fb.group({
   city: [null, Validators.required),
   comboDescription: [null, Validators.required),
   label: [null, Validators.required),
   price: [null, [Validators.required, Validators.min(1)]),
   productsIds: this.fb.array([], Validators.required),
   qtyIds: this.fb.array([], Validators.required)
 })
}

// create getters to retrieve the form array controls from the parent form group
public get productsIds(): FormArray {
  return this.myForm.get('productsIds') as FormArray;
}

public get qtyIds(): FormArray {
  return this.myForm.get('qtyIds') as FormArray;
}

// create methods for adding and removing productsIds
public addProduct(): void {
  this.productsIds.push(this.fb.control('', [Validators.required]));
}

public removeProduct(index: number): void {
  if(this.productsIds.length < 1) {
   return;
 }

  this.productsIds.removeAt(index);
}

// do the same for the qtyIds

In the template:

<form [formGroup]="myForm">
  .
  .
  .
  // example for productsIds
  <div formArrayName="productsIds">
    <button (click)="addProducts()">Add Product</button>

    <div *ngFor="let productId of productsIds.controls; index as i">
      <input type="text" [formControlName]="i">
      <button (click)="removeProduct(i)">Remove Product</button>
    </div>
  </div>
  .
  .
  .
</form>

Upvotes: 1

Related Questions