Search code examples
angularangular-reactive-formsformarray

Store and display input message in formArray


I have created an input field where the user can enter a message and on keyup enter I want to display this message.

export class AppComponent  {
 
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }


  onEnter() {
    this.addThing();
  }

  get things() {
    return this.myForm.get('things') as FormArray;
  }

  private createForm() {
    this.myForm = this.fb.group({
      things: this.fb.array([
        this.fb.control('')
      ])
    });
  }

  private addThing() {
    this.things.push(this.fb.control(''));
  }
}

Html:

<div class="display-text">
                            <p
                               *ngFor="let thing of things.controls; let i=index">{{thing.value}}
                            >
                                {{ message.value | json}}
                            </p>
                        </div>
<div class="input">
                <form [formGroup]="myForm">
                    <ng-container formArrayName="things">
                        <ng-container
                            ngFor="let thing of things.controls; let i = index "
                        >
                            <input
                                type="text"
                                (keyup.enter)="onEnter()"
                            />
                        </ng-container>
                    </ng-container>
                </form>
            </div>

When pressing enter, the message is not displayed in the window. Can someone help?

The Problem seems to be that no value is being stored in the formArray

enter image description here


Solution

  • I don't see you actually needing a formgroup here, I would just use a formcontrol for the input and a formarray or even just a "regular" JS array, I would probably use just that, but here is anyway sample of usage of formarray:

    TS:

    myInput = this.fb.control('');
    things = this.fb.array([]);
    
    constructor(private fb: FormBuilder) {}
    
    addThing() {
      this.things.push(this.fb.control(this.myInput.value)); // push value to formarray
      this.myInput.reset(); // reset input field
    }
    

    and template:

    <input [formControl]="myInput" (keyup.enter)="addThing()" />
    
    <p *ngFor="let thing of things.controls">
      {{ thing.value }}
    </p>
    

    STACKBLITZ