Angular 2 Angular 2 Data Driven Forms

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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



Got any Angular 2 Question?