简体   繁体   中英

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)': '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;
    }
}

And use in in this way:

<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" />

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.

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

This way you can plug into the ngModel handling.

See this question for more details:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM