Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply required validation to dropdown in angular 2

Tags:

angular

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.

like image 717
amol Avatar asked Jun 21 '16 11:06

amol


People also ask

What is validators required in angular?

A validator is a function that processes a FormControl or collection of controls and returns an error map or null. A null map means that validation has passed.


2 Answers

I have used *ngIf syntax, but you can provide validation on dropdown like :

<div class="form-group">
    <div>
        <label for="country">Country*:</label>
    </div>
    <div ng-class="{'valid':country.$valid}">
        <select class="form-control" name='country' [(ngModel)]='fd.country' required>
            <option *ngFor="let obj of country" [ngValue]="obj">{{obj}}</option>
        </select>
    </div>
    <small *ngIf="(myForm._submitted && !country.valid && !fd.country) || (!country.valid && country.dirty) ">Required (Please select country).</small>
</div>
like image 54
GsMalhotra Avatar answered Oct 15 '22 16:10

GsMalhotra


<div class="form-group select-box">
  <select class="form-control select_style1" [(ngModel)]='car.model' formControlName='model' #model>
    <option value="" >Select Model</option>
    <option value="option1b">Option 1</option>
    <option value="option2b">Option 2</option>
    <option value="option3b">Option 3</option>
  </select>
  <span *ngIf="modelForm.get('model').hasError('required') && modelForm.get('model').touched" class='error' padding>Model is a required field.</span>
</div>

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NgForm, FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
car: any={}
modelForm: FormGroup;
  constructor(public route: Router) {
    this.modelForm = new FormGroup({
      make: new FormControl('', [Validators.required]),
      model: new FormControl('', [Validators.required])

    })
   }

  ngOnInit() {
  }

  enterPin() {
    this.route.navigate(['enter-pin-code'])
  }
}
<div class="form-group select-box">
<select class="form-control select_style1" [(ngModel)]='car.model' formControlName='model' #model>
<option value="" >Select Model</option>
<option value="option1b">Option 1</option>
<option value="option2b">Option 2</option>
<option value="option3b">Option 3</option>
</select>
<span *ngIf="modelForm.get('model').hasError('required') && modelForm.get('model').touched" class='error' padding>Model is a required field.</span>
</div>
like image 45
gauri mishra Avatar answered Oct 15 '22 15:10

gauri mishra