Ghàith Mn
Ghàith Mn

Reputation: 45

ANGULAR: Select required validation issue

im trying to build a spring boot and angular application which allows user to upload a file and enter the file's tag and list of departement so I am using select html tag and I am binding list to it. I want a required validation if dropdown is not selected and showing 'Select' on its header.

console error:

ERROR TypeError: Cannot read property 'valid' of undefined

here's my html code

<div class="main-content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-12" data-aos="fade-right">
        <label class="btn btn-default">
          <input type="file" (change)="selectFile($event)" />
        </label>
      </div>
    </div>
    <div class="row">
      <div class="col-md-4" data-aos="fade-right">
        <div class="form-group">
          <label for="form"><h5>Tag</h5></label>
          <input
            type="text"
            class="form-control"
            id="tag"
            [(ngModel)]="tag"
            required
          />
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-4" data-aos="fade-right">
        <label for="form"
          ><h5>Departement: click to select departement</h5></label
        >
        <div class="form-group">
          <select
            name="departement"
            [(ngModel)]="dep"
            class="form-control selectpicker"
            required
          >
            <option
              *ngFor="let departement of departements"
              [value]="departement"
              >{{ departement }}</option
            >
          </select>
        </div>
        <small
          *ngIf="
            (!departement.valid && !dep) ||
            (!departement.valid && departement.dirty)
          "
          >Required (Please select Departement).</small
        >
      </div>
    </div>
    <div class="row" style="margin-bottom: 100px;">
      <div class="col-md-6">
        <button
          class="btn btn-success"
          [disabled]="!selectedFiles"
          (click)="upload()"
          style="background-color: #09c0a3;"
        >
          Upload
        </button>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12"></div>
    </div>
  </div>
</div>

Upvotes: 0

Views: 454

Answers (1)

Artem Krasniuk
Artem Krasniuk

Reputation: 1187

Save ngModel state to the template variable:

<select     #dptControl="ngModel"
            name="departement"
            [(ngModel)]="dep"
            class="form-control selectpicker"
            required
          >

<small
          *ngIf="
            (!dptControl.valid && !dep) ||
            (!dptControl.valid && dptControl.dirty)
          "
          >Required (Please select Departement).</small
        >

Tip: Use Reactive Forms instead of Template Driven forms

Upvotes: 0

Related Questions