How to automatically add an asterisk (*) for required fields in the reactive form using Angular

This article describes a method for automatically adding an asterisk (*) to required fields in a reactive form using Angular. It uses the built-in validators in Angular to determine if a field is required and then uses a component to add the asterisk to the label of the corresponding form field.

December 17, 2021 angularangular-forms

You can view the source code for this project by following this link: GitHub

Demo

Take note that clicking into buttons causes adding or removing *.

How to check if control is required?

Since Angular 13 is the available method to check if a control has a Validators.required validator. To do it use a hasValidator method.

1
import { FormControl, Validators } from "@angular/forms";
2
3
const title = new FormControl(null, [Validators.required]);
4
const isTitleRequired = title.hasValidator(Validators.required);
5
6
console.log(isTitleRequired); // -> true

Having this information you can dynamically add an asterisk (or not) in the template.

1
<label for="title"> Title {{ isTitleRequired ? "*" : ""}} </label>

Creating a custom wrapper for label

The next step is to create a component with formControl input and wrap label with custom logic.

1
import { Component, Input } from "@angular/core";
2
import { AbstractControl, Validators } from "@angular/forms";
3
4
@Component({
5
selector: "app-label",
6
template: `
7
<label [for]="for">
8
<ng-content></ng-content>
9
{{ required ? "*" : "" }}
10
</label>`,
11
styles: [
12
`
13
:host {
14
display: contents;
15
}
16
`,
17
],
18
})
19
export class AppLabelComponent {
20
@Input() for?: string;
21
@Input() formControl!: AbstractControl;
22
23
get required(): boolean {
24
return this.formControl.hasValidator(Validators.required);
25
}
26
}

Last but not least is to use app-label instead of label.

1
<div>
2
<app-label for="title" [formControl]="title">Title</app-label>
3
<input id="title" [formControl]="title" />
4
</div>

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment