简体   繁体   中英

Angular reactive form - Disable material design buttons in FormGroup

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

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.

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

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

Stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM