app.module.ts
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {HttpModule} from '@angular/http'; import {AppComponent} from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ReactiveFormsModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
app.component.ts
import {Component, OnInit} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { genders = ['male', 'female']; signupForm: FormGroup; ngOnInit(): void { this.signupForm = new FormGroup({ 'username': new FormControl(null), 'email': new FormControl(null), 'gender': new FormControl('male') // default value for radiobutton => male }) ; } onSubmit() { console.log(this.signupForm); } }
app.component.html
<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" class="form-control" formControlName="username"> </div> <div class="form-group"> <label for="email">email</label> <input type="text" id="email" class="form-control" formControlName="email"> </div> <div class="radio" *ngFor="let gender of genders"> <label> <input type="radio" [value]="gender" formControlName="gender">{{ gender }} </label> </div> <button class="btn btn-primary" type="submit">Submit</button> </form> </div> </div> </div>
References
https://angular.io/guide/reactive-forms