Angular 6 add input on enter key

Angular

Angular Problem Overview


I have component called text-editor.component and this is my html template:

<div class="container">

<div id="testo" class="offset-1 text-center" >
  <input type="text" class="col-8 text-center">
 </div>
</div>

I want to add a new input text when I press the enter key. This is what I'm trying to achieve:

<div id="testo" class="offset-1 text-center" >
  <input type="text" class="col-8 text-center">
  <!-- second input -->
  <input type="text" class="col-8 text-center">
 </div>
</div>

when the user presses enter after inputting text into the input, a new input should spawn. I am using Angular's template driven forms.

Angular Solutions


Solution 1 - Angular

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.

Solution 2 - Angular

Controller

Declare an array 'inputs' and initialises it with a value of 1.

inputs = [1];

Create a function addInput().

addInput() {
  this.inputs.push(1);
}

HTML

<div id="testo" class="offset-1 text-center" *ngFor="let more of inputs">
<input type="text" class="col-8 text-center" (keyup.enter)="addInput()">
</div>

In your template you'll be calling the addInput() function every time you hit enter (keyup.enter). The function pushes a new value into the array, whose length increases by 1 and that in turn creates a new input field.

Solution 3 - Angular

You can easily use keydown event in angular 6, angular 7, angular 8 and angular 9 application.

When user will key up on input box field then trigger onKeyDownEvent() of angular component. You can use (keydown.enter) attribute as to call function. Bellow logic code:

.html

<input type="search" (keydown.enter)="onKeyDownEvent($event)" />

.ts

@Component({
  selector: 'my-app',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css']

})
export class MyComponent {

  
  constructor(private router: Router,
              private route: ActivatedRoute) { }

  onKeyDownEvent(event: any) {
    this.router.navigate(['search-result'], { relativeTo: this.route });
    ...logic

  }
}

Be aware that we need to navigate to other route programmatically, in the .ts file, NOT in html file with the routerLink="/search-result" . We need to inject Router and ActivatedRoute classes as to navigate from current route to the /search-result route.

Solution 4 - Angular

I see a lot people using either keyup.enter or keydown.enter, but what is most appropriate is keypress.enter

<input type="text" [(ngModel)]="reference_num" class="form-control" placeholder="Type Reference number" name="reference_num" (keypress.enter)="search()">

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGJCodeView Question on Stackoverflow
Solution 1 - AngularAlexander StaroselskyView Answer on Stackoverflow
Solution 2 - Angularkaveripatnam.vivekView Answer on Stackoverflow
Solution 3 - Angularbyte is 8bitsView Answer on Stackoverflow
Solution 4 - AngularBuchiView Answer on Stackoverflow