【问题标题】:How to apply required validation to dropdown in angular 2如何将所需的验证应用于 Angular 2 中的下拉列表
【发布时间】:2016-06-21 11:26:30
【问题描述】:

我正在使用 select html 标记,我正在绑定列表。如果未选择下拉菜单并在其标题上显示“选择”,我需要进行必需的验证。

【问题讨论】:

    标签: angular


    【解决方案1】:

    我使用了*ngIf 语法,但您可以在下拉列表中提供验证,例如:

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

    【讨论】:

      【解决方案2】:
      <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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-11
        • 1970-01-01
        • 2017-09-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多