Home > Software design >  HTML & Angular Material disable save button from outside div when form fields are empty
HTML & Angular Material disable save button from outside div when form fields are empty

Time:06-10

I have the following Angular Material form with the Close and Save buttons in an outside div for design reasons:

<h1 mat-dialog-title>Product Page</h1>
<div mat-dialog-content>
    <form [formGroup]="productForm">
        <mat-form-field appearance="outline">
            <mat-label>Name</mat-label>
            <input formControlName="name" required matInput placeholder="Name" style="text-transform:uppercase">
        </mat-form-field>
        <mat-form-field appearance="outline">
            <mat-label>Weight</mat-label>
            <input type="number" required formControlName="weight" matInput placeholder="weight">
        </mat-form-field>
    </form>
</div>
<div mat-dialog-actions [align]="'end'">
    <button mat-raised-button color="warn" mat-dialog-close>Close</button>
    <button mat-raised-button color="primary" (click)="saveProduct()">Save</button>
</div>

I want to disable the Save button when the form fields are empty but the required parameter isn't working since the buttons are in an outside div. Is there a way to correlate the buttons with the form such that the Save button is disabled until the required fields are filled in?

CodePudding user response:

You can bind it manually :

  <button (click)="submit()" [disabled]="!form.valid">Submit</button>

Or you can cheat your way in the modal by providing the form as the main container (yes, it works)

  <form [formGroup]="form">
    <h1 mat-dialog-title>...</h1>
    <div mat-dialog-content>...</div>
    <div mat-dialog-actions align="end">
      <button type="submit" [disabled]="!form.valid">Submit</button>
    </div>
  </form>

CodePudding user response:

You could add a validation to your formGroup and use the formGroup to set the button disabled:

on your component:

constructor(fb:FormBuilder
 (...)
) {
   this.productForm = fb.group({
     name: [null, Validators.required]
     (...)  
   })
}

then on your template, adjust the button:

<button mat-raised-button color="primary" [disabled]="productForm.invalid" (click)="saveProduct()">Save</button>

You might as well remove the 'required' from you input (as angular will warn you about this in the console):

<input formControlName="name" matInput placeholder="Name" style="text-transform:uppercase">
  • Related