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>