Angular 6在回车键上添加输入

标签 angular

我有一个名为 text-editor.component 的组件,这是我的 html 模板:

<div class="container">

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

我想在按下回车键时添加一个新的输入文本。这就是我要实现的目标:

<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>

当用户在输入框内输入文本后按下回车键时,会产生一个新的输入框。我正在使用 Angular 的模板驱动表单。

最佳答案

您可以使用 Reactive Forms FormArray 来解决这个问题.你会附上一个 (keyup)(keyup.enter) <input /> 的处理程序.在这个 keyup 的处理程序中事件,我们推送一个新的FormControlFormArray .此示例使用 FormBuilder生成 FormGroup包含 FormArray key 为 things .我们使用 push FormArray的方法|添加一个新的 FormControl/AbstractControl在 keyup 的处理程序中。

组件:

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(''));
  }
}

模板:

<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>

在最基本的层面上,您可以使用 controls 遍历表单数组中的每个各自的属性(property) FormArray元素和值使用 value属性:

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

这是一个StackBlitz演示功能。

关于Angular 6在回车键上添加输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52375765/

相关文章:

javascript - 在所有类/接口(interface)/函数前面加上 App 首字母缩略词是个好习惯吗?

angular - 错误 TS2687 : All declarations of 'observable' must have identical modifiers

ios - 类型错误 : Cannot read property 'name' of undefined ionic

angular - agm-marker onMouseOver 打开 agm-info-window

angular - 如何将 angular 4 通用应用程序部署到 firebase

javascript - 在 Typescript 中使用外部 javascript 文件中的对象

angular - 在 Jest 单元测试 Angular 中显示正确的错误

node.js - 带有 GRPC 的 Angular Universal

css - Angular2 获取窗口宽度 onResize

node.js - Angular 4 具有通用 "Unexpected token import"