Search code examples
angularangular-forms

How to achieve required in select box in Angular 5?


I have the following template in Angular 5 app:

<div class="form-group">    
    <select [(ngModel)]="trip.country.code" (ngModelChange)="onSelectCountry($event)" name="country" required>
        <option>Please select...</option>
        <option *ngFor="let c of countries" value= {{c.country.code}}>{{c.country.name}}</option>
    </select>    
</div>

As you can see above, I have countries list and another option to inform the user to select. The problem is that I'm not sure how/when Angular make this field mark as invalid ? I select "Please select..." and I can see in the developer tools that the class is ng-untouched ng-pristine ng-valid Thanks!


Solution

  • We also came across similar problem in our application we resolved it with the following approach.

    The first select option we want it but we don't want to accept it as a valid input. so just mark it disable which will make the option available to user but the end user will not be able to select it. code as follow :

    <option [ngValue]="null" disabled>Please select...</option>
    

    check this example on stackblitz