のいずれかの解決策はあります。
唯一の特別なことは、数字入力でcontrol.value
が設定されることになる初期化されていないnull
を明示的に探していることです。
必要-number.validator.ts
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, Validators, ValidatorFn } from '@angular/forms';
function validateRequiredNumberFactory() : ValidatorFn {
return (control: AbstractControl) => {
let isValid = !isNaN(control.value) && control.value !== null;
console.log('isNaN: ' + isNaN(control.value));
if(isValid) {
return null;
}
return { numberIsRequired: true };
}
}
@Directive({
selector: '[requiredNumber][ngModel]',
providers: [{provide: NG_VALIDATORS, useExisting: RequiredNumberValidatorDirective, multi: true}]
})
export class RequiredNumberValidatorDirective implements Validator, OnChanges {
private valFn = Validators.nullValidator;
constructor() {
this.valFn = validateRequiredNumberFactory();
}
validate(control: AbstractControl): {[key: string]: any} {
return this.valFn(control);
}
}
入力はこのようです:
<input requiredNumber name="someName" [(ngModel)]="myProperty" #namedInput="ngModel"/>
は、ここでは、あなたの好みに合わせて、それはだhttp://plnkr.co/edit/gxTxOQBg8ilFHzgq4Ly0
クレジットを微調整することができplunkerですこの回答が由来したhttp://juristr.com/blog/2016/11/ng2-template-driven-form-validators/
私は主に、すべてのテンプレートのコード内と外の私のバリデータとの反応性のフォームを使用して。