Angular 4 reactive forms
In this tutorial, I am going to discuss reactive forms or model-driven forms.
Step 1. Add Following reference in app.module.ts
import { FormsModule , ReactiveFormsModule } from ‘@angular/forms’;
Step 2. Create New Component reactiveformex and add following code in reactiveformex.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators , ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-reactiveformex',
templateUrl: './reactiveformex.component.html',
styleUrls: ['./reactiveformex.component.css']
})
export class ReactiveformexComponent implements OnInit {
EMAIL_REGEX = "[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*";
registrationForm: FormGroup;
constructor() { }
ngOnInit() {
this.registrationForm = new FormGroup({
fname: new FormControl('', Validators.required),
lname: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.pattern(this.EMAIL_REGEX)])
});
}
onSubmit(formvalue)
{
console.log(formvalue);
console.log(this.registrationForm.value);
}
}
Step 3: Add following code in reactiveformex.component.html
<p>
reactiveformex works!
</p>
<form novalidate [formGroup]="registrationForm" (ngSubmit)="onSubmit(registrationForm.value)">
<input type="text" class="form-control" formControlName="fname" >
<div class="error-message" *ngIf="registrationForm.get('fname').touched && registrationForm.get('fname').hasError('required')">
The First name is required.
</div>
<input type="text" class="form-control" formControlName="lname" >
<div class="error-message" *ngIf="registrationForm.get('lname').touched && registrationForm.get('lname').hasError('required')">
The Last name is required.
</div>
<input type="email" class="form-control" formControlName="email">
<div class="error-message" *ngIf="registrationForm.get('email').touched && registrationForm.get('email').hasError('required')">
The email is required.
</div>
<div class="error-message" *ngIf="registrationForm.get('email').touched && registrationForm.get('email').hasError('pattern')">
The email format should be <i>yogeshdotnet@gmail.com</i> </div>
<button type="submit" class="btn btn-secondary" [disabled]="registrationForm.invalid">Submit</button>
</form>
Step 4: Add reference of reactiveformex component into app.component.html and run (ng serve –o)
Output

HEllo iakdjkvn
very good for nice work