Angular
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 32: <strong>Angular</strong> 2 Data Driven Forms<br />
Section 32.1: Data driven form<br />
Component<br />
import {Component, OnInit} from '@angular/core';<br />
import {<br />
FormGroup,<br />
FormControl,<br />
FORM_DIRECTIVES,<br />
REACTIVE_FORM_DIRECTIVES,<br />
Validators,<br />
FormBuilder,<br />
FormArray<br />
} from "@angular/forms";<br />
import {Control} from "@angular/common";<br />
@Component({<br />
moduleId: module.id,<br />
selector: 'app-data-driven-form',<br />
templateUrl: 'data-driven-form.component.html',<br />
styleUrls: ['data-driven-form.component.css'],<br />
directives: [FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES]<br />
})<br />
export class DataDrivenFormComponent implements OnInit {<br />
myForm: FormGroup;<br />
constructor(private formBuilder: FormBuilder) {}<br />
ngOnInit() {<br />
this.myForm = this.formBuilder.group({<br />
'loginCredentials': this.formBuilder.group({<br />
'login': ['', Validators.required],<br />
'email': ['', [Validators.required, customValidator]],<br />
'password': ['', Validators.required]<br />
}),<br />
'hobbies': this.formBuilder.array([<br />
this.formBuilder.group({<br />
'hobby': ['', Validators.required]<br />
})<br />
])<br />
});<br />
}<br />
removeHobby(index: number){<br />
(this.myForm.find('hobbies')).removeAt(index);<br />
}<br />
onAddHobby() {<br />
(this.myForm.find('hobbies')).push(new FormGroup({<br />
'hobby': new FormControl('', Validators.required)<br />
}))<br />
}<br />
}<br />
onSubmit() {<br />
console.log(this.myForm.value);<br />
}<br />
GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 125