Angular 6 add input on enter key

You can approach this using Reactive Forms FormArray. You would attach an (keyup) or (keyup.enter) handler to the <input />. Within the handler for this keyup event, we push a new FormControl to a FormArray. This example uses FormBuilder to generate a FormGroup that contains a FormArray with a key of things. We use the push method of FormArray to add a new FormControl/AbstractControl within the handler for keyup.

Component:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
    
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name="Angular";
  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([
        // create an initial item
        this.fb.control('')
      ])
    });
  }
    
  private addThing() {
    this.things.push(this.fb.control(''));
  }
}

Template:

<form [formGroup]="myForm">
    <div formArrayName="things">
        <div *ngFor="let thing of things.controls; let i=index">
            <label [for]="'input' + i">Thing {{i}}:</label>
            <input type="text" [formControlName]="i" [name]="'input' + i" [id]="'input' + i" (keyup.enter)="onEnter()"  />
        </div>
    </div>
</form>

At a very basic level you can loop through each in the form array using the controls property of the respective FormArray element and the value using the value property:

<ul>
  <li *ngFor="let thing of things.controls">{{thing.value}}</li>
</ul>

Here is a StackBlitz demonstrating the functionality.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)