角度观看输入值

时间:2018-04-14 09:34:12

标签: angular input reactive-programming elementref

观察输入HTML元素的值的最佳做法是什么?我需要动态添加尽可能多的输入。因此,我无法使用ngModel。此时我正在使用ElementRef

<div class="item">
    <input type="text" id="firstName1">
    <input type="text" id="lastName1">
</div>

我试图创建一个对象,其中值适应变化:

let user = {
   firstName: ADAPT_TO_FIRSTNAME_VALUE,
   lastName: ADAPT_TO_LASTNAME_VALUE
}

解决方案方法:

<form [formGroup]="user">
    <input type="text" formControlName="firstName">
    <input type="text" formControlName="lastName">
</form>


arr = new FormArray();
user;

create() {
    this.user = new FormGroup({
         firstName: new FormControl(),
         lastName: new FormControl()
    });
    this.arr.push(user);
}

1 个答案:

答案 0 :(得分:1)

这样的事情应该让你开始。

import { Component,  } from '@angular/core';
import { FormGroup, FormControl, FormBuilder } from '@angular/forms'

@Component({
  selector: 'my-app',
  template: `
  <form [formGroup]="form">
    <input *ngFor="let control of controls" [formControl]="control" />
  </form>

  {{ user | json }}
  `,
  styles: [`input { width: 100%; }`]
})
export class AppComponent {
  form: FormGroup;
  controls: FormControl[];

  get user() {
    return this.form.value;
  }

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      firstName: '',
      lastName: '',
      // add as much properties as you like
    })

    this.controls = Object.keys(this.form.controls).map(key => this.form.controls[key] as FormControl);
  }
}

我们为每个用户对象属性创建一个FormControl<input> html元素中的任何更改都将反映在FormGroup的值中。

请注意,我使用的是ReactiveFormsModule,您必须将其导入AppModule

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  imports: [BrowserModule, ReactiveFormsModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

Live demo