Skip to main content

How do you check if a control has an error?

You can check whether a control has an error using the hasError() method or the errors property.

Examples:

1. Via hasError():

typescript
this.form.get('email')?.hasError('required'); // true if the required error is present

2. Via the errors property:

typescript
this.form.get('email')?.errors; // returns an object like { required: true, email: true } or null

3. In the template:

html
<input formControlName="email"> <div *ngIf="form.get('email')?.hasError('required') && form.get('email')?.touched"> Field is required </div>

If errors is null: there are no errors. If it is an object: validation has failed.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.