====== Reactive Form ======
This example shows how to create a reactive form in code, and bind it to the HTML UI.
Codes are form https://www.udemy.com/course/the-complete-guide-to-angular-2/learn/lecture/6656504#overview. His course is good, I learn most of the Angular stuff from him.
===== reactive-form.component.ts =====
First we create a ''FormGroup'' instance in our code. Then we setup the struct of this from group on ''ngOnInit''. Notice that the names inside the form control. Those are ''formControlName'', and we are going to use them to bind to our HTML UI.
import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup} from "@angular/forms";
@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.component.html',
styleUrls: ['./reactive-form.component.css']
})
export class ReactiveFormComponent implements OnInit {
genders = ['male', 'female'];
signupForm: FormGroup;
constructor() {
}
ngOnInit() {
this.signupForm = new FormGroup({
'username': new FormControl(null),
'email': new FormControl(null),
'gender': new FormControl('male')
});
}
onSubmit() {
console.log(this.signupForm);
}
}
===== reactive-form.component.html =====
First we bind our HTML form to our formGroup by putting ''[formGroup]="signupForm"'' inside the form tag. For each input tag, we put the corresponding ''formControlName'' in it, and it MUST match to the name we defined in ''ngOnInit()''.