Search code examples
angularangular-formsmat-select

Send button doesn't work with mat-select required validation in angular template driven form


In my Angular application there is a template driven form.

 <form #deviceForm="ngForm" (ngSubmit)="onSendClickHandler()"> 
 <div class="form-group col-md-2">
  <section>
    <mat-checkbox
          color="primary"
          #confirmed1
          >Product</mat-checkbox>
  </section>
 </div>

<div class="form-group col-md-2">
  <mat-form-field class="mat-form-field" appearance="outline">
    <mat-label>Select Product</mat-label>
      <mat-select
      [disabled]="!confirmed1.checked" required>
        <mat-option *ngFor="let product of productlist" [value]="product.code">
          {{product.name}}
        </mat-option>
      </mat-select>
  </mat-form-field>
 </div>

 <button
   class="btn btn-primary btn-space " 
   type="submit"
   mat-button
   [disabled]="!deviceForm.valid">
   Send
  </button>
 </form>

When form is loading drop down list and send buttons are disabled. After click the checkbox it should be enable and when select any from list send button should be enable.

My problem is when I select product from list send button doesn't enable. Validation is working.


Solution

  • Couple missing things in your approach:

    1. you need to add a name to your controls
    2. you need to end these controls with an ngModel

    reference: https://www.pluralsight.com/guides/difference-between-template-driven-and-reactive-forms-angular?aid=7014Q000002DU4oQAG&promo=&oid=&utm_source=non_branded&utm_medium=digital_paid_search_google&utm_campaign=US_Dynamic_ProgrammingLanguages&utm_content=&utm_term=17331039103&gclid=Cj0KCQjw0oyYBhDGARIsAMZEuMsuQ147q_OfpirfAxwu-SUTNApINfVLyixOrLPdgcbGf6kcb-sPAEoaAkBVEALw_wcB

    I would highly recommend you use reactive forms instead of template driven, template driven is the older approach and it is clearly inferior to reactive forms.

    However, here is a small working stackblitz of how to make your code work. I did rename your device form to myForm, and I came up with a model for product list.

    https://stackblitz.com/edit/angular-wro6wq?file=src/app/app.component.ts