DEV Community

Faisal Ahmed
Faisal Ahmed

Posted on

Form Array Practice

      <div>
        <h2>Menus Data Store</h2>
        <div formArrayName="menus">
          <div *ngFor="let data of menusDataArray?.controls; let i = index">
            <input type="text" [formControlName]="i">
<button (click)="removeFormArrayField('menus', i)" class="delete">Delete</button>
          </div>
          <button (click)="onAddNewFormString('menus')">Add Menus</button>
        </div>
      </div>
Enter fullscreen mode Exit fullscreen mode
  // Form Array
  menusDataArray?: FormArray;

private initDataForm() {
    this.dataForm = this.fb.group({
      name: [null, Validators.required],
      menus: this.fb.array([
        this.createStringElement()
      ]),
    });

    this.menusDataArray = this.dataForm.get('menus') as FormArray;
  }

  createStringElement() {
    return this.fb.control('');
  }

  onAddNewFormString(formControl: string) {
    (this.dataForm?.get(formControl) as FormArray).push(this.createStringElement());
    console.log("this.menusDataArray --->", this.menusDataArray );

  }


  removeFormArrayField(formControl: string, index: number) {
    let formDataArray: FormArray;
    switch (formControl) {
      case 'menus': {
        formDataArray = this.menusDataArray;
        break;
      }
      default: {
        formDataArray = null;
        break;
      }
    }
    formDataArray?.removeAt(index);
  }


Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay