Пользовательский валидатор Angular 4 не работает для тега select
У меня есть две формы в двух разных модальностях, и я применяю пользовательский валидатор для Иностранной валюты, который является раскрывающимся списком. Валидатор сравнивает выбранное значение с другим раскрывающимся списком, который является Базовой валютой, если значения совпадают, отображается ошибка. он отлично работает на createTradeForm, но не работает на форме tradeEdit
Вот createTradeForm в HTML-шаблон
<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>
и вот моя форма TradeEdit в HTML шаблон
<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">×</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]
})
}
и вот пользовательский валидатор формы createTrade для ForeignCurrency
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 для валюты foreidgn
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;
}
}