2

观察输入 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);
}
4

1 回答 1

1

Something like this should get you started.

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

We create one FormControl for each user object property. Any change in the <input> html element will be reflected in the FormGroup's value.

Please note that I'm using the ReactiveFormsModule and you must import it in your 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

于 2018-04-14T10:02:49.140 回答