1

I have to create a dynamic form where label and input fields will both are text-field(user will fill at run time). And user can add as many as fields he requires. I have requirements where I have to generate. property file in backend. Where key-value pair is required and the user decides how much key-value pair he needs.

enter image description here

1
  • 1
    You need to use FormArray of FormGroup. You should share your code. Commented Sep 29, 2021 at 21:16

1 Answer 1

1

Create FormGroup as

  keyValueFA = new FormArray([this.newKeyValueFG]);

  propertyFG = new FormGroup({
    keyValue: this.keyValueFA,
  });

getter to create new FormGroup

  get newKeyValueFG(): FormGroup {
    return new FormGroup({
      key: new FormControl(null),
      value: new FormControl(null),
    });
  }

Other methods to set, remove, get FormGroup

  get keyValueArrayFGControls(): FormGroup[] {
    return this.keyValueFA.controls as FormGroup[];
  }

  addNewKeyValueFG(): void {
    this.keyValueFA.push(this.newKeyValueFG);
  }

  removeNewKeyValueFG(index: number): void {
    this.keyValueFA.removeAt(index);
  }

In template iterate keyValueArrayFGControls

<form [formGroup]="propertyFG">
  <div
    formArrayName="keyValue"
    *ngFor="let fg of keyValueArrayFGControls; let i = index"
  >
    <div [formGroup]="fg">
      {{ i + 1 }})
      <div><input type="text" formControlName="key" placeholder="Key" /></div>
      <div>
        <input type="text" formControlName="value" placeholder="Value" />
      </div>
      <button (click)="removeNewKeyValueFG(i)">Remove</button>
    </div>
  </div>
  <button (click)="addNewKeyValueFG()">Add</button>
</form>

Working demo

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

2 Comments

Once data is added and we want to update data how we would do that.
You mean Once data is added in Form; you want to save it in db by API call?

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.