Can't update bind value on blur or on setValue

I have a number which is bound to localValue. I would, when I hit maximum value on set(localValue) or on blur, update value for upper max value (in sample is 50).

But it seem it work only once after set or blur didn’t work anymore (blur never work).

PlunkerSample

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Test On blur update with valid value (Value max is 50)</h2>
      <h2>If you type 9999 --> 5099</h2>
      <input type="number" [(ngModel)]="localValue" (blur)="OnLostFocus()"/>
    </div>
  `
})

  private localValue: number;

  public set localValue(value: number) {
    if(value > 50){
      value = 50;
    }

    this._localValue = value;
  }

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

You would define your variable this way: private _localValue: number; I’m not sure that using the blur event is necessary in your case since the value is managed by setters and getters. See this plunkr: https://plnkr.co/edit/rDsX72pSGxFAnBuDPHfq?p=preview. Edit I would create rather a custom value accessor for your input. 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);… Read more »