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()
.
<div class="container"> <div class="row"> <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2"> <form [formGroup]="signupForm" (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="username">Username</label> <input type="text" id="username" formControlName="username" class="form-control"> </div> <div class="form-group"> <label for="email">email</label> <input type="text" id="email" formControlName="email" class="form-control"> </div> <div class="radio" *ngFor="let gender of genders"> <label> <input formControlName="gender" type="radio" [value]="gender">{{ gender }} </label> </div> <button class="btn btn-primary" type="submit">Submit</button> </form> </div> </div> </div>