2.角prevent输入模型中使用的指令改变 [英] Angular 2. Prevent input and model changing using directive
问题描述
我需要验证域:在范围内唯一的数字。所以,我试着写了这样的指令:
I need to validate field: only numbers in range. So, i have tried to write such directive:
@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模式的价值。
But it is some big problem: 1. This limitation fired AFTER angular 2 model changed, so i will get 0 value in model (but i need 1 as a min value). 2. This just change input value, but not angular 2 model value.
那么,是不是可以验证和prevent一改之前棱角分明模型的一些投入?
So, is it possible to validate and prevent some inputs before angular model changed?
推荐答案
我应该使用自定义值的访问来实现这一点。这里有一个例子:
I should use a custom value accessor to implement this. Here is a sample:
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
处理。
有关详细信息,请参阅此问题:
See this question for more details:
- Can't在模糊或setValue方法 更新绑定值
- Can't update bind value on blur or on setValue
这篇关于2.角prevent输入模型中使用的指令改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!