如何对角度2的下拉列表应用所需的验证 [英] How to apply required validation to dropdown in angular 2

查看:48
本文介绍了如何对角度2的下拉列表应用所需的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用select html标记,并且将其绑定到列表.如果没有选择下拉菜单,并且在标题上显示选择",我希望进行必要的验证.

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.

推荐答案

<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>

这篇关于如何对角度2的下拉列表应用所需的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆