Angular 2 Prevent Input And Model Changing Using Directive
I need to validate a field to only have numbers in a range. So I have tried to write a directive: @Directive({ selector: '[input-limitation]', host: { '(input)': 'o
Solution 1:
I should use a custom value accessor to implement this. Here is a sample:
constCUSTOM_VALUE_ACCESSOR = newProvider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() =>MaxValueAccessor), multi: true});
@Directive ({
selector: 'input[max]',
host: { '(input)': 'doOnChange($event.target)' },
providers: [ CUSTOM_VALUE_ACCESSOR ]
})
exportclassMaxValueAccessorextendsDefaultValueAccessor {
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);
}
}
This way you can plug into the ngModel
handling.
See this question for more details:
Post a Comment for "Angular 2 Prevent Input And Model Changing Using Directive"