1

I want to disable (or enable) a FormGroup based on a boolean input of my component

export class MyFormComponent implements OnInit {
  form: FormGroup;
  @Input() isDisabled: boolean;

  ngOnInit(): void {
    this.form = this.fb.group({
    // ...

All the answers that I found said it's bad practice to use <form [formGroup]="form" [disabled]="isDisabled" in the template, and to use this.form.disable(); in the typescript instead, most of them are also using old versions of Angular.

Is there any good solution to do this in the template and avoid extra code with a recent Angular (16+)?

1 Answer 1

1

You can write a reusable custom directive:

@Directive({
  selector: '[formGroup][formGroupDisabled]',
  standalone: true,
})
export class FormGroupDisabledDirective {
  /** Form group instance */
  @Input({ required: true }) formGroup?: FormGroup;
  /** Whether the form group is disabled or not */
  @Input({ required: true, transform: booleanAttribute })
  set formGroupDisabled(disabled: boolean) {
    if (!this.formGroup) {
      return;
    }
    if (disabled && this.formGroup.enabled) {
      this.formGroup.disable();
    } else if (!disabled && this.formGroup.disabled) {
      this.formGroup.enable();
    }
  }
}

And use it like the following in the template:

<form [formGroup]="formGroup" [formGroupDisabled]="someBooleanFlag">
Sign up to request clarification or add additional context in comments.

3 Comments

I would suggest using input.required instead of @Input
@T.Jami The author asked for an Angular 16 solution, input.required does not exist in this version. Also it's still in developer preview.
16+, but yeah, my bad :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.