import { Component } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-sample-form', template: ` <input [formControl]="nameControl" aria-label="Name input" /> <div *ngIf="nameControl.invalid && (nameControl.dirty || nameControl.touched)" role="alert"> Name is required. </div> `, standalone: true }) export class SampleFormComponent { nameControl = new FormControl('', Validators.required); }
Angular shows validation errors when the control is invalid and either touched or dirty. This means the user interacted with the input and then left it empty, triggering the error message.
<input [formControl]="formControl" /> <div *ngIf="formControl.invalid && formControl.touched">Error</div>
The *ngIf directive syntax is correct and the condition uses valid properties of the form control. No syntax error exists.
The FormControl has an empty validators array, so it never becomes invalid. Without a required validator, the control is always valid even if empty.
import { FormControl, Validators } from '@angular/forms'; const control = new FormControl('abc', [Validators.required, Validators.minLength(5)]); const errors = control.errors;
The input is not empty, so required passes. But length is less than 5, so minlength error appears with details.
The touched and dirty properties indicate if the user has focused or changed the input, so errors show only after interaction.
