像这样的事情应该让你开始。
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: '',
})
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