1

I have a reactive form containing Angular material design components. I want to disable all controls in the form while the component is being initialized1.

I have tried to call disable() on the FormGroup in the constructor as well as in ngOnInit(), but for some reason buttons (using material design) in the form remains enabled.

Stackblitz

The template:

<form [formGroup]="emailForm">
  <mat-form-field>
    <input matInput type="email" formControlName="email" placeholder="Email" />
  </mat-form-field>
  <button formControlName="removeButton" mat-icon-button class="button-small" (click)="clearEmail()" matTooltip="Clear email address" matTooltipClass="tooltip-medium" [matTooltipShowDelay]="500" ngDefaultControl>
    <mat-icon aria-label="Clear">clear</mat-icon>
  </button>
</form>

The component:

export class EmailFormComponent implements OnInit {
  private emailForm: FormGroup;

  constructor(private formbBuilder: FormBuilder) {
    this.createReactiveForm();
  }

  ngOnInit() {
     this.emailForm.disable();
  }  

  createReactiveForm() {
    this.emailForm  = this.formbBuilder.group({
      email: ['', [Validators.email, Validators.maxLength(100)]],
      removeButton : ['']
    });

    this.emailForm.disable();
  }

  clearEmail() {
    this.emailForm.patchValue({email:''});
  }
}

If I remove material design from the button it gets disabled during initialization. If I call this.emailform.disable()from a click eventHandler method in the component the button in the form also gets disabled.

Is it a bug that the button doesn't get disabled during initialization or am I doing something wrong? How do I make the button disabled in the UI at initialization?

(Note: This is a simplified example. The real application has more input fields in the form).

1 When I asked this question I was unfamiliar with Angular's resolve guard which can be used to load dynamic data before navigating to a component.

2
  • 1
    Can you make sure that the stackblitz you provided was working?? For me it is showing not found.. Hope this stackblitz.com/edit/… helps.. Commented Aug 20, 2019 at 11:28
  • Thanks for noticing. Please try again now Commented Aug 20, 2019 at 11:32

1 Answer 1

1

You shouldn't use form control for button. Just disable form and use button disabling like:

<button [disabled]="emailForm.disabled" ...

Stackblitz

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.