YouTube Icon

How to Display Validation or Error Messages in Angular Forms




How to Display Validation or Error Messages in Angular Forms

Introduction 

Angular is making it simpler to fabricate applications for the web. Angular consolidates reliance infusion and revelatory layouts, and it has coordinated accepted procedures to take care of advancement issues. 

Structures are perhaps the most widely recognized highlights in any application. Clients can utilize structures to sign in, book a flight, or request food. You can improve the general information quality by approving client contribution for exactness. 

This aide will cover how to show approval or mistake messages with Angular structures.

Also Read:- Top Reasons to choose Angular Today

Create a New Angular Project

Install Angular globally by using the following command.

npm install -g @angular/cli

Then type below command to create a new Angular project.

ng new ngValidation

Add a few files and install some dependencies. Navigate to the root app directory and type the following command to start the server.

cd my-app
ng serve --open

You'll create a form with a single input to get an understanding of Angular forms. First, you must include reactive forms in app.module.ts.

// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    BrowserModule, ReactiveFormsModule
  ],

Also Read:- List of Procedural Programming Languages

Now, we can add the below code to display the form.

<div style="text-align:left">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <form [formGroup]="myForm" novalidate>
        <div class="form-group">
          <label class="center-block">Username:
            <input class="form-control" formControlName="username">
          </label>
        </div>
        <div *ngIf="myForm.controls['username'].invalid && (myForm.controls['username'].dirty || myForm.controls['username'].touched)" class="alert">
            <div *ngIf="myForm.controls['username'].errors.required">
            Please enter username
          </div>
        </div>
  </form>
<p>myForm value: {{ myForm.value | json }}</p>
<p>myForm status: {{ myForm.status | json }}</p>
</div>

You also need to update the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'My Angular Form Validation Example';
   myForm: FormGroup;
   constructor(private fb: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.myForm = this.fb.group({
       username: ['', Validators.required ]
    });
  }
}

Template Driven Forms 

You can make a format driven structure in Angular layout grammar utilizing the structure mandates. Construct layout driven structures by following these means: 

  • Make another Angular segment with an underlying structure design. 
  • Add information properties to tie for each structure control and add a property to each shape input control. 
  • Show/shroud approval messages. 
  • Handle structure submit utilizing ngSubmit. 
  • Discretionary: Add highlight to handicap the submit button at first and empower solely after the structure is legitimate. 

Also Read:- Top 10 Companies Which Built their Apps with AngularJS and Node.js

Receptive Forms 

Receptive structures are utilized to make frames that contain a responsive style. A receptive way of writing computer programs is empowered by Angular responsive structures that supports nitty gritty administration of the information streaming between a non-UI information model (normally recovered from a worker) and a UI-arranged structure model that contains the states and upsides of the HTML controls on the screen. Receptive structures give the solace of using responsive examples, testing, and approval. 

How about we take a gander at a model.

import { Component } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Form Validation Tutorial';
   myForm: FormGroup;
   constructor(private fb: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.myForm = this.fb.group({
       username: ['', Validators.required ]
    });
  }
}

Here, you need to import a few modules from @angular/forms.

  • FormGroup
  • FormBuilder
  • Validators and ReactiveFormsModule
// app.component.ts

constructor(private fb: FormBuilder) {
    this.createForm();
}

Also Read:- How to get selected radio button value in AngularJS?

Use a FormBuilder to handle validations. Create a form with all the validation rules inside the constructor.

// app.component.ts

createForm() {
  this.myForm = this.fb.group({
       username: ['', Validators.required ]
  });
}

Assign the validation rules to the form object in this code.

<form [formGroup]="myForm" novalidate>
        <div class="form-group">
          <label class="center-block">Username:
            <input class="form-control" formControlName="username">
          </label>
        </div>
        <div *ngIf="myForm.controls['username'].invalid && (myForm.controls['username'].dirty || myForm.controls['username'].touched)" class="alert">
            <div *ngIf="myForm.controls['username'].errors.required">
            Please enter username
          </div>
        </div>
  </form>
<p>Form value: {{ myForm.value | json }}</p>
<p>Form status: {{ myForm.status | json }}</p>

Conclusion

You have now seen both layout driven structures and responsive structures. At the point when a client contacts any info field however doesn't enter a worth, a blunder message will be shown. Once more, when the client obscures the information field without entering a worth, a blunder message will be shown. Along these lines, we can show approval messages for the structure fields.

Also Read:- What you pick in 2020 : ReactJS vs AngularJS vs VueJS

 



Author Biography.

Lokesh Gupta
Lokesh Gupta

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working in the information technology and services industry. I enjoy solving complex problems within budget and deadlines putting my skills on PHP, MySQL, Python, Codeigniter, Yii2, Laravel, AngularJS, ReactJS, NodeJS to best use. Through Knowledge of UML & visual modeling, application architecture design & business process modeling. Successfully delivered various projects, based on different technologies across the globe.

Join Our Newsletter.

Subscribe to CrowdforThink newsletter to get daily update directly deliver into your inbox.

CrowdforGeeks is where lifelong learners come to learn the skills they need, to land the jobs they want, to build the lives they deserve.

CrowdforGeeks

CrowdforThink is a leading Indian media and information platform, known for its end-to-end coverage of the Indian startup ecosystem.

CrowdforThink

Our mission is "Har Koi Dekhe Video, Har Ghar Dekhe Video, Ghar Ghar Dekhe Video" so we Provide videos related to Tutorials, Travel, Technology, Wedding, Cooking, Dance, Festivals, Celebration.

Apna Video Wala
CFT

News & Blogs

6acf7d9983a7af2862934dada02293b3.png

10 Reasons To Choose AngularJS For Web Development

In this digital era, an online presence is a must if you have a business. It is because the mobil...

cc5e89d77946d7c5846df189394b6e4c.jpg

A Brief Guide to Hire AngularJs Developer in th...

Are you looking for web app development for your business? And want to hire AngularJS developers ...

b155c4808d155c5ed54a2d70f917f6ea.png

An Introduction to Angular: The Remarkable JS F...

Javascript frameworks have nowadays become the most popular and most-used web app development sol...

Top Authors

Lamia Rochdi is the Marketing Manager at Bell Flavors & Fragrances EMEA. A successful family-...

Lamia Rochdi

I’m Mertin Wilson a technician in a camera company and certified expert of different P...

Mertin Wilson

Zakariya has recently joined the PakWheels team as a Content Marketing Executive, shortly after g...

Zakariya Usman

Pankaj Singh is a Senior Digital Marketing Consultant with more than 2 years of experience in SEO...

Pankaj Singh
CFT

Our Client Says

WhatsApp Chat with Our Support Team