Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate error messages for nested form group fields in angular

Hi i am new for angular and i am trying to implement form validations and using below code and my problem is nested form group fields i am getting errors in log TypeError: Cannot read property 'touched' of null can some one help me please..

.ts

 ngOnInit() {
    this.employeeForm = this.fb.group({
      fullName: ['',[Validators.required,Validators.minLength(2), Validators.maxLength(10)]],
      email: ['',[Validators.required,Validators.email]],
      skills: this.fb.group({
        skillName: ['',[Validators.required]],
        experienceInYears: ['',Validators.required],
        proficiency: ['']
      })
    });
  }

.html

<form class="form-horizontal" [formGroup]="employeeForm" (ngSubmit)="onSubmit()">

  <div class="panel panel-primary">
    <div class="panel-heading">
      <h3 class="panel-title">Create Employee</h3>
    </div>

    <div class="panel-body">

      <div class="form-group" [ngClass]="{'has-error':((employeeForm.get('fullName').touched ||
      employeeForm.get('fullName').dirty) &&
      employeeForm.get('fullName').errors)}">
        <label class="col-sm-2 control-label" for="fullName">Full Name</label>
        <div class="col-sm-8">
          <input id="fullName" type="text" class="form-control" formControlName="fullName">
          <span class="help-block" *ngIf="((employeeForm.get('fullName').touched ||
          employeeForm.get('fullName').dirty) &&
          employeeForm.get('fullName').errors)">
            <span *ngIf="employeeForm.get('fullName').errors.required">
              Full Name is required
            </span>
            <span *ngIf="employeeForm.get('fullName').errors.minlength ||
                   employeeForm.get('fullName').errors.maxlength">
              Full Name must be greater than 2 characters and less than 10 characters
            </span>
          </span>
        </div>
      </div>

      <div class="form-group" [ngClass]="{'has-error':((employeeForm.get('email').touched ||
      employeeForm.get('email').dirty) &&
      employeeForm.get('email').errors)}">
        <label class="col-sm-2 control-label" for="email">Email</label>
        <div class="col-sm-8">
          <input id="email" type="text" class="form-control" formControlName="email">
          <span class="help-block" *ngIf="((employeeForm.get('email').touched ||
          employeeForm.get('email').dirty) &&
          employeeForm.get('email').errors)">
            <span *ngIf="employeeForm.get('email').errors.required">
              Email is required
            </span>
            <span *ngIf="employeeForm.get('email').errors.email">
              Valid Email is required
            </span>
          </span>
        </div>
      </div>

    //**PROBLEM IN THIS BLOCK**
      <div formGroupName="skills">

        <div class="form-group" [ngClass]="{'has-error':((employeeForm.get('skillName').touched ||
        employeeForm.get('skillName').dirty) &&
        employeeForm.get('skillName').errors)}">
          <label class="col-sm-2 control-label" for="skillName">skill Name</label>
          <div class="col-sm-4">
            <input type="text" class="form-control" formControlName="skillName">

            <span class="help-block" *ngIf="((employeeForm.get('skillName').touched ||
            employeeForm.get('skillName').dirty) &&
            employeeForm.get('skillName').errors)">
              <span class="help-block" *ngIf="employeeForm.get('skillName').errors.required">
                Skill is required
              </span>
            </span>
          </div>
          <div class="col-sm-4">
            <input type="text" class="form-control" formControlName="experienceInYears">
            <span class="help-block" *ngIf="((employeeForm.get('experienceInYears').touched ||
            employeeForm.get('experienceInYears').dirty) &&
            employeeForm.get('experienceInYears').errors)">
              <span class="help-block" *ngIf="employeeForm.get('experienceInYears').errors.required">
                Experience is required
              </span>
            </span>
          </div>

        </div>

      </div>

    </div>

<div class="panel-footer">
  <div class="btn-toolbar">
    <button class="btn btn-primary" type="submit">Save</button>
    <button class="btn btn-primary" type="submit" (click)="onLoadDataClick()">Load Data</button>
  </div>
</div>

like image 699
Krish Avatar asked Nov 27 '18 09:11

Krish


People also ask

What is Abstractcontrol in Angular?

It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like value , valid , and dirty . It shouldn't be instantiated directly.

How to add a validator to the formgroup in Angular 2?

To add a validator to the FormGroup, pass the new validator in as the second argument on creation. The validator code is as follows. The identity validator implements the ValidatorFn interface. It takes an Angular control object as an argument and returns either null if the form is valid, or ValidationErrors otherwise.

How to show form validation error messages on the form?

There are various ways to show the Validation error messages on the form, In Angular, if you are using Angular Material as UI tool and you wan to show the Form Validation message, then follow the below steps to add Angular Material Form Group Validation and show validation error messages on the web page dynamically as you start typing:

How to validate a formarray in angular?

Angular FormArray tracks the value and validity state of an array of FormControl, FormGroup or FormArray instances. To create a FormArray, we can pass an array of FormControl or FormGroup. A FormArray is called validated only if its FormControl or FormGroup are validated. We can validate FormArray with synchronous and async validators.

How to display error messages in Angular Material?

In angular material we have different selector present which can be used to show our error messages. mat-error: This is used to show the error, with the message attached to it. If the form is invalid then this message will be appear on screen with red color. 3.


Video Answer


1 Answers

Be aware of the fact that, you have nested your form one level by folder called, 'skills'. Hence, you need to honor that by,

employeeForm.get('skills.skillName').touched
like image 140
Ashokan Sivapragasam Avatar answered Oct 23 '22 11:10

Ashokan Sivapragasam