Angular markAsTouched() Example
In this article, we will learn to use markAsTouched()
method in our Angular application.
1. The markAsTouched()
is the method of AbstractControl
that is the base class for FormControl
, FormGroup
, and FormArray
.
2. A control is considered to be touched by focus and blur events that do not change the value. We can programmatically mark a control touched using following methods of AbstractControl
.
a. markAsTouched() : Marks a control as touched.
b. markAllAsTouched() : Marks the control and all its descendant controls as touched.
3. The touched is a boolean property of AbstractControl
that has true value if the control is marked as touched.
4. Here we will learn to use markAsTouched()
method. We can use it in the scenario where we want to validate required before submit. We can call markAsTouched()
method before submitting the form to check whether the form is validated or not.
Using markAsTouched()
The markAsTouched()
is the method of AbstractControl
. As we know that AbstractControl
is the base class for FormControl
, FormGroup
, and FormArray
. Hence markAsTouched()
can be called by FormControl
, FormGroup
, and FormArray
.
The declaration of markAsTouched()
from Angular doc is as following.
markAsTouched(opts: { onlySelf?: boolean; } = {}): void
When onlySelf is true, mark only this control as touched. If the value of onlySelf is false i.e. default, or not supplied, then the method marks all direct ancestors as touched.
Suppose we have created a form as following.
teamForm: FormGroup = this.formBuilder.group({ teamName: ['', Validators.required], teamManager: ['', Validators.required], employees: this.formBuilder.array([ new FormControl('', [Validators.required]), new FormControl('', [Validators.required]) ]) });
Now call markAsTouched()
on the form controls.
1. For FormControl
:
this.teamForm.get('teamName')?.markAsTouched(); this.teamForm.get('teamManager')?.markAsTouched();
2. For FormArray
:
this.teamForm.get('employees')?.markAsTouched();
3. For FormGroup
:
this.teamForm.markAllAsTouched();
Find the code to use onlySelf with markAsTouched()
method.
this.teamForm.get('teamName')?.markAsTouched({onlySelf: true});
For the value of onlySelf as
true : marks only self as touched.
false : marks all direct ancestors as touched. This is default value.
Complete Example
Here I am creating an example that has a form with some controls. The form controls have required validator. In the situation when a user hits submit button without filling required data, I will use markAsTouched()
method to display error messages.
team-management.component.ts
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormArray, Validators, FormBuilder, ReactiveFormsModule, FormControl } from '@angular/forms'; import { TeamManagementService } from './team-management.service'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-team', standalone: true, imports: [ CommonModule, ReactiveFormsModule ], templateUrl: './team-management.component.html' }) export class TeamManagementComponent implements OnInit { teamForm = {} as FormGroup; formSubmitted = false; constructor( private formBuilder: FormBuilder, private teamMngService: TeamManagementService) { } ngOnInit() { this.createTeamForm(); } createTeamForm() { this.teamForm = this.formBuilder.group({ teamName: ['', Validators.required], teamManager: ['', Validators.required], employees: this.formBuilder.array([ new FormControl('', [Validators.required]), new FormControl('', [Validators.required]), ]) }); } get employees(): FormArray { return this.teamForm.get('employees') as FormArray; } onFormSubmit() { if (this.teamForm.valid) { this.teamMngService.saveTeam(this.teamForm.value); this.formSubmitted = true; this.teamForm.reset(); } else { this.teamForm.get('teamName')?.markAsTouched({onlySelf: true}); this.teamForm.get('teamManager')?.markAsTouched(); this.teamForm.get('employees')?.markAsTouched(); this.formSubmitted = false; //this.teamForm.markAllAsTouched(); } } }
team-management.component.html
<h3>Demo: markAsTouched()</h3> <div *ngIf="formSubmitted && teamForm.pristine" class="submitted"> Form submitted successfully. </div> <div class="team"> <form [formGroup]="teamForm" (ngSubmit)="onFormSubmit()"> <p>Team Name* : <input formControlName="teamName"> <br /><label *ngIf="teamForm.get('teamName')?.touched && teamForm.get('teamName')?.hasError('required')" class="error"> Team name required. </label> </p> <p>Team Manager* : <input formControlName="teamManager"> <br /><label *ngIf="teamForm.get('teamManager')?.touched && teamForm.get('teamManager')?.hasError('required')" class="error"> Manager name required. </label> </p> Employees in Team* : <br><br> <div formArrayName="employees"> <div *ngFor="let emp of employees.controls; let idx = index"> <input [formControlName]="idx"> <br/><br/> </div> <label *ngIf="teamForm.get('employees')?.touched && teamForm.get('employees')?.invalid" class="error"> Employees required. </label> </div> <button>SUBMIT</button> </form> </div>
team-management.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class TeamManagementService { saveTeam(data: any) { const team = JSON.stringify(data); console.log(team); } }
Find the print screen of the output.