Javascript 角度2使用指令防止输入和模型更改

Javascript 角度2使用指令防止输入和模型更改,javascript,angular,Javascript,Angular,我需要验证一个字段是否只有一个范围内的数字。所以我试着写一个指令: @Directive({ selector: "[input-limitation]", host: { '(input)': 'onChange($event)', } }) export class InputLimitationDirective { @Input("input-limitation") settings: InputLimitationSettings;

我需要验证一个字段是否只有一个范围内的数字。所以我试着写一个指令:

@Directive({
    selector: "[input-limitation]",
    host: {
        '(input)': 'onChange($event)',
    }
})
export class InputLimitationDirective {
    @Input("input-limitation") settings: InputLimitationSettings;

    public constructor(private el: ElementRef) {
        let self = this;
        console.log(":::::::::::::::: el.nativeElement", el.nativeElement);
        //jQuery(el.nativeElement).on('keypress', function (e) { self.onChange(e) });
    };

    private onChange($event) {

        console.log("InputLimitationDirective", this.settings);

        if (this.settings.InputType = "number") {
           return this.numberLimitation($event);
        }
    }

    private numberLimitation($event: any) { 
        let val: number = $event.target.value;
        console.log("InputLimitationDirective", val);
        console.log(val, this.settings.MinValue);
        console.log(!val, val*1 < this.settings.MinValue*1);

        if (!val || val*1 <= this.settings.MinValue*1) {
            console.log("1 case");
            event.preventDefault();
            event.stopPropagation();
            return false;
        }
        else if (val*1 >= this.settings.MaxValue*1) {
            console.log("2 case");
            event.preventDefault();
            event.stopPropagation();
            return false;
        };

        return true;
    }
}
@指令({
选择器:“[输入限制]”,
主持人:{
“(输入):“onChange($event)”,
}
})
导出类InputLimitationDirective{
@输入(“输入限制”)设置:输入限制设置;
公共构造函数(私有el:ElementRef){
让自我=这个;
console.log(“:::::::el.nativeElement”,el.nativeElement);
//jQuery(el.nativeElement).on('keypress',函数(e){self.onChange(e)});
};
私有onChange($event){
log(“InputLimitationDirective”,this.settings);
如果(this.settings.InputType=“number”){
返回此.numberLimitation($event);
}
}
私有数字模仿($event:any){
让val:number=$event.target.value;
log(“InputLimitationDirective”,val);
log(val,this.settings.MinValue);
console.log(!val,val*1
并以这种方式使用:

<input (change)="totalAmountChanged($event.target.value)"
       [(ngModel)]="model.UsedVolume"
       [disabled]="!isEditMode"
       type="number"
       [input-limitation]="usedVolumeInputLimitationsSettings"
       pattern="^[1-9]\d*$" min="1" max="999" maxlength="3"
       class="form-control length-3-input" />

但这是一个大问题: 1.这个限制在Angular 2模型更改后触发,所以我将在模型中得到0值(但我需要1作为最小值)。 2.这只是更改输入值,而不是角度2模型值


那么,在角度模型更改之前是否可以验证和阻止某些输入?

我应该使用自定义值访问器来实现这一点。以下是一个示例:

const CUSTOM_VALUE_ACCESSOR = new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => MaxValueAccessor), multi: true});

@Directive ({
  selector: 'input[max]',
  host: { '(input)': 'doOnChange($event.target)' },
  providers: [ CUSTOM_VALUE_ACCESSOR ]
})
export class MaxValueAccessor extends DefaultValueAccessor {
  onChange = (_) => {};
  onTouched = () => {};

  writeValue(value:any):void {
    if (value!=null) {
      super.writeValue(value);
    }
  }

  doOnChange(elt) {
    var val = elt.value;
    // check value here
    elt.value = val;
    this.onChange(val);
  }
}
这样,您就可以插入
ngModel
处理

有关更多详细信息,请参见此问题: