To upgrade our form into an Angular form that can perform validation, we have to createFormControl andFormGroupobjects. A FormControl object represents a form control in a form. With it, we can track the value and validation status of an individual form control. AFormGroup object tracks the value and validity state of a group of FormControl objects.
Example
Step 1: Create new angular cli project.
Step2: Create new controller.
ng g c validationexample –flat
Step 3: Add following code into validationexample.component.html
<p> validationexample works! </p> <form [formGroup]="form" (ngSubmit)="login()"> <div class= "form-group"> <label for="username">User Name</label> <input type="text" formControlName="username" class="form-control" /> <div *ngIf="form.controls.username.touched && !form.controls.username.valid" class="alert alert-danger">Username is required </div> </div> <div class= "form-group"> <label for="password">Password</label> <input type="text" formControlName="password" class="form-control" /> <div *ngIf="form.controls.password.touched && !form.controls.password.valid" class="alert alert-danger">Password is required</div> </div> <input class="btn btn-primary" [disabled]="form.invalid" type="submit" value="Submit" /> </form>
Step4: Add following code into validation.component.ts
import { Component, OnInit } from '@angular/core'; import { FormGroup , FormControl ,Validators, NgForm} from '@angular/forms'; @Component({ selector: 'app-validationexample', templateUrl: './validationexample.component.html', styleUrls: ['./validationexample.component.css'] }) export class ValidationexampleComponent { // create formgroup object and add formcontrol to perform validations form = new FormGroup({ username: new FormControl('', Validators.required), password: new FormControl('', Validators.required) }); login() { console.log(this.form.value); } }
Step 5: Pass reference of newly created component(validationexample) to app.component.html
<h2>App Component</h2> <app-validationexample></app-validationexample>
Step 6: Run application
ng serve –open
Output:
this example is not working
plz can u check one time
but thanks a lot for wonderful tutorials