Stats

144 Contributors: 2 Sunday, December 18, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Angular 2 Data Driven Forms

Remarks

this.myForm = this.formBuilder.group

creates a form object with user's configuration and assigns it to this.myForm variable.


'loginCredentials': this.formBuilder.group

method creates a group of controls which consist of a formControlName eg. login and value ['', Validators.required], where the first parameter is the initial value of the form input and the secons is a validator or an array of validators as in 'email': ['', [Validators.required, customValidator]],.


'hobbies': this.formBuilder.array

Creates an array of groups where the index of the group is formGroupName in the array and is accessed like :

<div *ngFor="let hobby of myForm.find('hobbies').controls; let i = index">
   <div formGroupName="{{i}}">...</div>
</div>

onAddHobby() {
    (<FormArray>this.myForm.find('hobbies')).push(new FormGroup({
      'hobby': new FormControl('', Validators.required)
    }))
  }

this sample method adds new formGroup to the array. Currently accessing requires specifing the type of control we want to access, in this example this type is : <FormArray>


removeHobby(index: number){
    (<FormArray>this.myForm.find('hobbies')).removeAt(index);
  }

same rules as above apply to removing a specific form control from the array

Related Examples