Search code examples
javascriptangularvalidationangular-materialdropdown

How to make dropdownlist required in angular material?


I have a search 'form' with angular material. But it is not a form with a submit button. But just a button. like this:

  <button mat-raised-button color="accent" class="Button" (click)="searchFor()">Filter</button>

and I have a dropdownlist. But I want to make the dropdownlist required.

Like this:

 <div class="search-select searchstatus" *ngIf="selectedSearch && hasStatusOptions(selectedSearch)">
        <mat-select placeholder="Status" name="option"  [(ngModel)]="selectedValue" required>
          <mat-option *ngFor="let option of getStatusOptions(selectedSearch)"  [value]="option.apiStatus">
            {{ option.status }}
          </mat-option>
        </mat-select>
      </div>

But his doesnt work.

So how to make the dropdownlist required? Thank you

For datepicker it works. If I do this:

   <input matInput readonly required [matDatepicker]="picker1" placeholder="start datum" [(ngModel)]="startDate" />

Then if there is no date entered the label becomes red and there is showing a *

if I do this:

   <mat-select  #statusSelect placeholder="Status" name="option"  [(ngModel)]="selectedValue" [required]="true" >

and this:

   <button [disabled] = '!statusSelect.value' mat-raised-button color="accent" class="Button" (click)="searchFor()">Filter</button>

I get this error:

ExtendedSearchComponent.html:62 ERROR TypeError: Cannot read property 'value' of undefined

Solution

  • I am guessing from the information provided that you want to select a value from the dropdown and filter based on that. So, you can disable the filter till a value is selected in the dropdown. Maybe something like this.

    <div>
        <mat-select placeholder="Status" name="option"  [(ngModel)]="selectedValue" required>
           <mat-option></mat-option>
           <mat-option *ngFor="let option of tableDef"  [value]="option">
                {{ option.header }}
           </mat-option>
           </mat-select>
     </div>
    
    <button mat-raised-button color="accent" class="Button" (click)="searchFor()" [disabled]="!selectedValue">Filter</button>
    

    Edit:-

    I saw your comments above after the edit. Instead of using the css selector (#statusSelect.value), you can directly check by the object you are binding to the [(ngModel)] i.e "selectedValue"