I have developed a unique custom input element that showcases its label when a required constraint is present (calculated in the OnInit method).
@Component({
selector: 'custom-input',
template: `<div *ngIf="isMandatory()">Mandatory</div><input/>`
})
export class CustomInput implements ControlValueAccessor, OnInit {
mandatory = false;
constructor(
@Self()
@Optional()
public ngControl: NgControl
) {
super(ngControl);
}
ngOnInit(): void {
this.mandatory = this.isMandatory();
}
public isMandatory(): boolean {
let mandatory = false;
if (this.ngControl) {
const errors = new FormControl('', this.ngControl.control.validator, this.ngControl.control.asyncValidator).errors;
mandatory = errors?.required;
}
return mandatory;
}
writeValue(value: string): void {
this.value = value;
}
...
If the constraint changes and I need to update the label to indicate that the input is now optional:
this.form = this.formBuilder.group({
custominput: new FormControl(null, Validators.required)
});
// remove required validator => I want to re-calculate the 'mandatory' variable
this.form.controls.customInput.clearValidators();
this.form.controls.customInput.updateValueAndValidity();
How can I dynamically update my label within the component without subscribing to statusChanges?
One solution I've discovered involves:
writeValue(value: string): void {
this.value = value;
this.mandatory = this.isMandatory();
}
...
this.form = this.formBuilder.group({
customInput: new FormControl(null, Validators.required)
});
this.form.controls.customInput.clearValidators();
// To trigger the writeValue function
this.form.controls.customInput.setValue(this.form.controls.customInput.value);
this.form.controls.customInput.updateValueAndValidity();