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.

import { FormControl, Validators } from "@angular/forms";

const title = new FormControl(null, [Validators.required]);
const isTitleRequired = title.hasValidator(Validators.required);

console.log(isTitleRequired); // -> true

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

<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.

import { Component, Input } from "@angular/core";
import { AbstractControl, Validators } from "@angular/forms";

@Component({
  selector: "app-label",
  template: `
  <label [for]="for">
    <ng-content></ng-content>
    {{ required ? "*" : "" }}
  </label>`,
  styles: [
    `
      :host {
        display: contents;
      }
    `,
  ],
})
export class AppLabelComponent {
  @Input() for?: string;
  @Input() formControl!: AbstractControl;

  get required(): boolean {
    return this.formControl.hasValidator(Validators.required);
  }
}

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

<div>
  <app-label for="title" [formControl]="title">Title</app-label>
  <input id="title" [formControl]="title" />
</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