首页 > 解决方案 > Angular 4自定义验证器不适用于选择标签

问题描述

我在两种不同的模式中有两种形式,我在外币上应用自定义验证器,这是一个下拉列表,验证器将选定的值与另一个下拉列表进行比较,如果值相同,则显示错误。它在 createTradeForm 上工作正常,但在 tradeEdit 表单上不起作用

这是 html 模板中的 createTradeForm

<div class="modal-content">
    <form  [formGroup]="createTradeEntryForm" class="form-horizontal ng-pristine ng-invalid ng-touched" enctype="multipart/form-data" ngnativevalidate="" ng-reflect-form="[object Object]">
                <div class="modal-header">
                    <h4 class="modal-title">Trade Entry</h4>
                    <button aria-label="Close" class="close" type="button" (click)="TradeEntryVm.hide()">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">   
                    <div class="card-block">

                        <div class="form-group row">
                                <label class="col-md-3 form-control-label" for="BaseCurrency">Currency 1</label>
                                <div class="col-md-9">
                                    <select formControlName="BaseCurrency" class="form-control ng-untouched ng-pristine ng-invalid" size ="1"  id="BaseCurrency" name="BaseCurrency" ng-reflect-required="required" ng-reflect-name="Base Currency">
                                        <option [selected]="true" disabled="" value="0" ng-reflect-value="0">Please select</option>
                                        <option value="1" ng-reflect-value="1">USD</option>
                                        <option value="2" ng-reflect-value="2">NZD</option>
                                        <option value="3" ng-reflect-value="3">AUD</option>
                                        <option value="4" ng-reflect-value="4">ZAR</option>
                                        <option value="5" ng-reflect-value="5">CHF</option>
                                        <option value="6" ng-reflect-value="6">CAD</option>
                                        <option value="7" ng-reflect-value="7">EUR</option>
                                        <option value="8" ng-reflect-value="8">GBP</option>
                                        <option value="9" ng-reflect-value="9">SGD</option>
                                        <option value="10" ng-reflect-value="10">ILS</option>

                                    </select>
                                </div>
                        </div>

                        <div class="form-group row">
                                <label class="col-md-3 form-control-label" for="ForeignCurrency">Currency 2</label>
                                <div class="col-md-9">
                                    <select formControlName="ForeignCurrency" class="form-control ng-pristine ng-invalid ng-touched" id="ForeignCurrency" name="ForeignCurrency" ng-reflect-required="required" ng-reflect-name="ForeignCurrency" >
                                        <option [selected]="true" disabled="" value="0" ng-reflect-value="0">Please select</option>
                                        <option value="1" ng-reflect-value="1">USD</option>
                                        <option value="2" ng-reflect-value="2">NZD</option>
                                        <option value="3" ng-reflect-value="3">AUD</option>
                                        <option value="4" ng-reflect-value="4">ZAR</option>
                                        <option value="5" ng-reflect-value="5">CHF</option>
                                        <option value="6" ng-reflect-value="6">CAD</option>
                                        <option value="7" ng-reflect-value="7">EUR</option>
                                        <option value="8" ng-reflect-value="8">GBP</option>
                                        <option value="9" ng-reflect-value="9">SGD</option>
                                        <option value="10" ng-reflect-value="10">ILS</option>
                                    </select>    
                                    <em *ngIf="ForeignCurrency.invalid && ForeignCurrency.dirty">Selected currency should be different from Base Currency!</em>
                                </div>
                        </div>

                    </div>

这是我的 html 模板中的 tradeEdit 表单

                <form [formGroup]="tradeEditForm"  class="form-horizontal ng-pristine ng-invalid" enctype="multipart/form-data" ngnativevalidate="" ng-reflect-form="[object Object]">
                    <div class="modal-header">
                        <h4 class="modal-title">Edit Trade</h4>
                        <button type="button" class="close" (click)="editModal.hide()" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body"> 
                        <div class="card-block" >

                            <div class="form-group row">
                                    <label class="col-md-3 form-control-label" for="BaseCurrency">Currency 1</label>
                                    <div class="col-md-9">
                                        <select formControlName="BaseCurrency" class="form-control ng-untouched ng-pristine ng-invalid" size ="1"  id="BaseCurrencyEdit" name="BaseCurrency" ng-reflect-required="required" ng-reflect-name="Base Currency">
                                            <option [selected]="true" disabled="" value="0" ng-reflect-value="0">Please select</option>
                                            <option value="1" ng-reflect-value="1">USD</option>
                                            <option value="2" ng-reflect-value="2">NZD</option>
                                            <option value="3" ng-reflect-value="3">AUD</option>
                                            <option value="4" ng-reflect-value="4">ZAR</option>
                                            <option value="5" ng-reflect-value="5">CHF</option>
                                            <option value="6" ng-reflect-value="6">CAD</option>
                                            <option value="7" ng-reflect-value="7">EUR</option>
                                            <option value="8" ng-reflect-value="8">GBP</option>
                                            <option value="9" ng-reflect-value="9">SGD</option>
                                            <option value="10" ng-reflect-value="10">ILS</option>
                                        </select>
                                    </div>
                            </div>
                            <div class="form-group row">
                                    <label class="col-md-3 form-control-label" for="ForeignCurrency">Currency 2</label>
                                    <div class="col-md-9">
                                        <select formControlName="ForeignCurrency" class="form-control ng-pristine ng-invalid ng-touched" id="ForeignCurrencyEdit" name="ForeignCurrency" ng-reflect-required="required" ng-reflect-name="ForeignCurrency" >
                                            <option [selected]="true" disabled="" value="0" ng-reflect-value="0">Please select</option>
                                            <option value="1" ng-reflect-value="1">USD</option>
                                            <option value="2" ng-reflect-value="2">NZD</option>
                                            <option value="3" ng-reflect-value="3">AUD</option>
                                            <option value="4" ng-reflect-value="4">ZAR</option>
                                            <option value="5" ng-reflect-value="5">CHF</option>
                                            <option value="6" ng-reflect-value="6">CAD</option>
                                            <option value="7" ng-reflect-value="7">EUR</option>
                                            <option value="8" ng-reflect-value="8">GBP</option>
                                            <option value="9" ng-reflect-value="9">SGD</option>
                                            <option value="10" ng-reflect-value="10">ILS</option>
                                        </select>    
                                        <em *ngIf="tradeEditForm.controls.ForeignCurrency.invalid && tradeEditForm.controls.ForeignCurrency.dirty">Selected currency should be different from Base Currency!</em>
                                        for curr dir: {{tradeEditForm.controls.ForeignCurrency.dirty}} <br>
                                        for inva cur: {{tradeEditForm.controls.ForeignCurrency.invalid}}
                                    </div>
                            </div>
                    </form>
            </div>
        </div>
</div>

这是组件

import {Component, OnInit, ViewChild} from '@angular/core';
import { DatepickerOptions } from 'ng2-datepicker';
toaster/angular2-toaster';
import { ModalDirective } from 'ng2-bootstrap/modal';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';

@Component({
    templateUrl: 'trade-entry.component.html',
  })
export class TradesComponent
 {
    InitilizeForm(): any {
      this.BaseCurrency =  new FormControl('',Validators.compose([Validators.required, Validators.pattern(".*\\S.*")]))
      this.ForeignCurrency =  new FormControl('',Validators.compose([SameCurrencyValidator("BaseCurrency"), Validators.pattern(".*\\S.*") ]))

      this.createTradeEntryForm = new FormGroup({
        // BlotterId: new FormControl(),
        AccountNo: new FormControl('',Validators.required),
        Type: new FormControl('', Validators.required),
        MarketRate:new FormControl('',Validators.required),
        BaseCurrencyAmount: new FormControl('', Validators.required),
        BaseCurrency: this.BaseCurrency,
        ForeignCurrencyAmount: new FormControl('', Validators.required),
        ForeignCurrency: this.ForeignCurrency,
        TradeDate:new FormControl(),
        SettlementDate: new FormControl(),
        // Status: new FormControl(),
        Comment:new FormControl('',Validators.required),
      })
    }
    InitilizeFormEdit(): any {
      this.BaseCurrencyEdit =  new FormControl('',Validators.compose([Validators.required, Validators.pattern(".*\\S.*")]))
      this.ForeignCurrencyEdit=  new FormControl('',Validators.compose([Validators.required, SameCurrencyValidatorEdit("BaseCurrency")]))
      this.tradeEditForm = new FormGroup({
        BlotterId: new FormControl(),
        AccountNo: new FormControl('', Validators.required),
        TradeDate:new FormControl('', Validators.required),
        Type: new FormControl('', Validators.required),
        MarketRate:new FormControl('',Validators.required),
        BaseCurrencyAmount: new FormControl('', Validators.required),
        BaseCurrency: this.BaseCurrencyEdit,
        ForeignCurrencyAmount: new FormControl('', Validators.required),
        ForeignCurrency: this.ForeignCurrencyEdit,
        SettlementDate: new FormControl('', Validators.required),
        // Status: new FormControl(),
        Comment:new FormControl('',Validators.required),
        // Status23: new FormControl(),

      })
    }
    ngOnInit(): void {
      this.InitilizeForm()
      this.InitilizeFormEdit()

      // this.tradesEntries=this.tradesEntrySerive.getEntries();
      this.LoggedinUser = this.authService.getCurrentUser()
      this.searchObjectHeader.UserRefId = this.LoggedinUser.UserRefId
      this.tradeDate=new Date()
      this.settlementDate =new Date()
      // this.tradesEntries=this.tradesEntrySerive.getEntries()

      this.getPage(1);

    }
      @ViewChild('TradeEntryVm') public TradeEntryVm: ModalDirective;
      @ViewChild('editModal') public EditModal: ModalDirective;
      @ViewChild('deleteModal') public DeleteModal:ModalDirective;
      @ViewChild('executeModal') public ExecuteModal:ModalDirective;
      p: number = 1;
      firstpage: number = 1;
      total: number;
      searchObjectHeader = {
        SherpaClientId: 0,
        UserType: 0,
        UserId: 0,
        UserRole:0,
        UserRefId:0,
        'Content-Type': "application/json; charset=utf-8"
      }
      searchObjectBody = {
        PageSize: 0,
        PageNumber: 0,
        TotalPages:100,
        TotalRecord:0,
        Text: ''
      }

      EditfromList(ob: any) {      this.getAccountList=this.accountService.getAllTradeAccounts(this.searchObjectHeader, this.searchObjectBody)
        .do(res => {
          if(res.Status==0)
          {
            this.toastSErvice.pop('error', 'Error', res.Error) 
            this.spinnerloading=false;       
          }
          else
        {
          if(res.Data.length==0)
          {
             this.emptyChk =true;
          }
          console.log(res)
        }
        })
        .map(res => res.Data);
        this.marketRate=ob.MarketRate
        this.offerAmount=ob.ForeignCurrencyAmount
        this.baseAmount=ob.BaseCurrencyAmount
        this.tradeDateEdit=ob.TradeDate
        this.settlementDateEdit=ob.SettlementDate
        console.log("foreign currency"+ ob.ForeignCurrency)
        this.tradeEditForm = this.fb.group({
          BlotterId: [ob.BlotterId],
          AccountNo: [ob.AccountNo],
          TradeDate:[ob.TradeDate],
          Type: [ob.Type],
          MarketRate:[ob.MarketRate],
          BaseCurrencyAmount: [ob.BaseCurrencyAmount],
          BaseCurrency: [ob.BaseCurrency],
          ForeignCurrencyAmount: [ob.ForeignCurrencyAmount],
          ForeignCurrency: [ob.ForeignCurrency],
          SettlementDate: [ob.SettlementDate],
          // Status:[ob.Status],
          Comment:[ob.Comment]
        })
      }          

这是foreignCurrency的createTrade表单自定义验证器

    import {FormControl} from '@angular/forms';


export function SameCurrencyValidator (otherControlName: string) {

  let thisControl: FormControl;
  let otherControl: FormControl;

  return function SameCurrencyValidate (control: FormControl) {

    if (!control.parent) {
      return null;
    }

    // Initializing the validator.
    if (!thisControl) {
      thisControl = control;
      otherControl = control.parent.get(otherControlName) as FormControl;
      if (!otherControl) {
        throw new Error('SameCurrencyValidator(): other control is not found in parent group');
      }
      otherControl.valueChanges.subscribe(() => {
        thisControl.updateValueAndValidity();
      });
    }

    if (!otherControl) {
      return null;
    }

    if (otherControl.value === thisControl.value) {
      return {
        matchOther: true
      };
    }

    return null;

  }

}

这是我用于外国货币的 editTradeForm 自定义验证器

import {FormControl} from '@angular/forms';


export function SameCurrencyValidatorEdit (otherControlName: string) {

  let thisControl: FormControl;
  let otherControl: FormControl;

  return function SameCurrencyValidateEdit (control: FormControl) {

    if (!control.parent) {
      return null;
    }

    // Initializing the validator.
    if (!thisControl) {
      thisControl = control;
      otherControl = control.parent.get(otherControlName) as FormControl;
      console.log(control.parent)
      if (!otherControl) {
        throw new Error('SameCurrencyValidatorEdit(): other control is not found in parent group');
      }
      otherControl.valueChanges.subscribe(() => {
        thisControl.updateValueAndValidity();
      });
    }

    if (!otherControl) {
      return null;
    }

    if (otherControl.value === thisControl.value) {
      var check = otherControl.value === thisControl.value
      console.log(check)
      return {
        matchOther: true
      };
    }

    return null;

  }

}

标签: angularformscustom-validators

解决方案


推荐阅读