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的模型值。
那麼,是否有可能在角度模型改變之前驗證和防止一些輸入?