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