• Angular
  • React
  • NextJs
  • Sass

Angular markAsUntouched() Example

By Webrecto, September 5, 2023

In this article, we will learn to use markAsUntouched() method in our Angular application.

1. The markAsUntouched() is the method of Angular AbstractControl class. The markAsUntouched() method marks the control as untouched.

2. A control is considered to be touched when focus and blur events occur that do not change the value. We can programmatically mark a control untouched using markAsUntouched() method of AbstractControl.

3. When we call markAsUntouched() on a control, the value of touched of that control is becomes false.

On this page, I will create a form validation application using markAsUntouched() method.

Using markAsUntouched()

markAsUntouched() is the method of AbstractControl class that marks the control as untouched.

markAsUntouched(opts: { onlySelf?: boolean; } = {}): void

When onlySelf is true, the method marks untouched only this control otherwise all direct ancestors are marked untouched. The default is false.

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 markAsUntouched() on the form controls.

1. For FormControl :

this.teamForm.get('teamName')?.markAsUntouched();
this.teamForm.get('teamManager')?.markAsUntouched();

2. For FormArray :

this.teamForm.get('employees')?.markAsUntouched();

3. For FormGroup :

this.teamForm.markAsUntouched();

Find the code to use onlySelf with markAsUntouched() method.

this.teamForm.get('teamName')?.markAsUntouched({onlySelf: true});

For the value of onlySelf as

true : marks untouched only self.

false : marks untouched all direct ancestors. This is default value.

Complete Example

In this example, I will create a reactive form with some controls with required validation. The validation messages are being shown when the controls are touched. To show the usability of markAsUntouched(), I will hide the validation messages using this method in our demo application. Now find the code.

team.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormArray, Validators, FormBuilder, ReactiveFormsModule, FormControl } from '@angular/forms';
import { TeamService } from './team.service';
import { CommonModule } from '@angular/common';

@Component({
	selector: 'app-team',
	standalone: true,
	imports: [
		CommonModule,
		ReactiveFormsModule
	],
	templateUrl: './team.component.html'
})
export class TeamComponent {
	formSubmitted = false;
	constructor(
		private formBuilder: FormBuilder,
		private teamService: TeamService) {
	}
	teamForm: FormGroup = 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.teamService.saveTeam(this.teamForm.value);
			this.formSubmitted = true;
			this.teamForm.reset();
		} else {
			this.teamForm.markAllAsTouched();
			this.formSubmitted = false;
		}
	}
	hideValMsg() {
		this.teamForm.get('teamName')?.markAsUntouched();
		this.teamForm.get('teamManager')?.markAsUntouched();
		this.teamForm.get('employees')?.markAsUntouched();
		//this.teamForm.markAsUntouched();
	}
}

team.component.html

<h3>Demo: markAsUntouched()</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 type="button" (click)="hideValMsg()">Hide Validation Messages</button>
      <br/><button>SUBMIT</button>
  </form>
</div>

team.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class TeamService {
   saveTeam(data: any) {
	const team = JSON.stringify(data);
	console.log(team);
  }
}

Find the print screen of the output.

Angular markAsUntouched() Example

Reference

Download Source Code