0

I have a local variable where the backend data is received as Array like:

itemsFromBackend: ["Item1", "Item2"]

Creating a new Array

items: FormArray

In formgroup:

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

Creating an item

createItem(): FormGroup {
  return this.formBuilder.group({
    name: ''
  });
}

Adding an item:

addItem(): void {
  this.items = this.form.get('items') as FormArray;
  this.items.push(this.createItem());
}

In HTML

<div formArrayName="items" *ngFor="let item of form.get('items').controls; let i = index ">
      <div *ngFor="let item of itemsFromBackEnd" [formGroupName]="i">
        <input value={{item}} />
        <section>
            <button
              mat-raised-button
              color="primary"
              type="button"
              (click)="addItem()"
            >
              <i class="material-icons"> add </i>
            </button>
          </section>
      </div>
    </div>

I'm now receiving two fields with the backend values, but when I click on the add button it should display a new input field, but it is adding another two input fields with the value of backend. I need some help in displaying a new input field when I click on the add button. Thank you.

1 Answer 1

1

With these changes, it behaves as you want

html:

<div [formGroup]="form">
  <div formArrayName="items" *ngFor="let item of getItems(); let i = index">
    <input value="{{ itemValue(item) }}" />
  </div>
  <section>
    <button mat-raised-button color="primary" type="button" (click)="addItem()">
     <i class="material-icons"> add </i>
    </button>
  </section>
</div>

ts:

itemsFromBackEnd = ['Item1', 'Item2'];
form: FormGroup;

constructor(private formBuilder: FormBuilder) {}

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

  this.itemsFromBackEnd.forEach(i => this.addItem(i));
 }

 getItems() {
   return (<FormArray>this.form.get('items')).controls;
 }

 itemValue(item: any) {
   return item.controls.value.value;
 }

 createItem(name?: string): FormGroup {
   return this.formBuilder.group({
     value: name ? name : ''
   });
}

addItem(name?: string): void {
   const items = this.form.get('items') as FormArray;
   items.push(this.createItem(name));
}
Sign up to request clarification or add additional context in comments.

Comments

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.