2016-04-21 103 views
1

防止輸入和模型更改我需要驗證字段:只有範圍內的數字。所以,我試圖寫這樣的指令:Angular 2.使用指令

@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; 
    } 
} 

並以這種方式使用:

 <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。 此限制解僱了角2模式改變,所以我會在模型中獲得0值(但我需要1作爲最小值)。 2.這只是改變輸入值,而不是角度2的模型值。

那麼,是否有可能在角度模型改變之前驗證和防止一些輸入?

回答

0

我應該使用自定義值存取器來實現這一點。這裏是一個樣本:

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處理。

詳情請參見這個問題: