I'm struggling with implementing a directive that can be applied to elements with the [formGroup] attribute in order to disable the entire form group and its form controls based on a condition, rather than manually calling this.formGroup.disable()
.
I found a directive for form controls online:
import { Directive, Input } from "@angular/core";
import { NgControl } from "@angular/forms";
// use this directive instead of manually enabling and disabling with reactive forms
@Directive({
selector: "([formControlName], [formControl])[disabledControl]",
})
export class DisabledControlDirective {
@Input() set disabledControl(condition: boolean) {
if (this.disabled !== undefined) {
this.toggleControl(condition);
}
this.disabled = condition;
}
disabled: boolean;
constructor(private readonly ngControl: NgControl) {}
ngOnInit() {
this.toggleControl(this.disabled);
}
toggleControl(condition: boolean) {
const action = condition ? "disable" : "enable";
this.ngControl.control[action]();
}
}
I attempted something similar for form groups:
import { Directive, Input } from "@angular/core";
import { ControlContainer } from "@angular/forms";
@Directive({
selector: "([formGroup])[disabledGroup]",
})
export class DisabledGroupDirective {
@Input() set disabledGroup(condition: boolean) {
if (this.disabled !== undefined) {
this.toggleGroup(condition);
}
this.disabled = condition;
}
disabled: boolean;
constructor(private readonly controlContainer: ControlContainer) {}
ngOnInit() {
this.toggleGroup(this.disabled);
}
toggleGroup(condition: boolean) {
const action = condition ? "disable" : "enable";
this.controlContainer.control[action]();
}
}
However, the form group is not being properly disabled. Even though the status shows as "DISABLED" in the debugger, when I resume the application, the form loads without being disabled. Further inspection via a button click reveals that the status has reverted back to "INVALID." Any insights on how to resolve this issue?
Edit: I created a basic Stackblitz demo, where it seems to work fine: https://stackblitz.com/edit/angular-ivy-owlvqu?file=src/app/app.component.ts
Edit2: No other parts of the code manipulate the form group, except for adding it to a parent formGroup using addControl() within ngOnInit(). Even after removing this part, the disabling functionality still doesn't work, unlike in the Stackblitz example. It's puzzling why the status keeps resetting.
As a workaround, I tried switching from ngOnInit() to ngAfterViewInit() in the group directive, and oddly, it worked - the form group got disabled. However, I'm unsure if this is the most elegant solution. Ideally, I would like to understand why the formGroup's status changes unexpectedly, as there are no other triggers in the code.