简体   繁体   中英

Angular X directive: the best way to handle ngModel value change

I have such directive, which handles onBlur/onFocus changes and adds $ symbol to the beginning of the input value:

@Directive({
  selector: "[inputChanger]",
  host: {
    "(focus)": "onFocus($event)",
    "(blur)": "onBlur($event)"
  }
})
export class InputChangerDirective implements OnChanges {
  @Input("inputChanger") type: string;

  @Input() serverValue: string;

  constructor(private model: NgModel, private el: ElementRef) {}

  ngOnChanges(changes) {
    if (changes.serverValue && changes.serverValue.currentValue) {
      setTimeout(() => {
        this.el.nativeElement.dispatchEvent(new Event("blur"));
      });
    }
  }

  onFocus(element: any) {
    element.target.value = this.model.model || "";
  }

  onBlur(element: any) {
    if (Number(this.model.model)) {
      element.target.value = "$" + Number(this.model.model);
    }
  }
}

I need to add this $ somehow when i blur my input or when data from the server comes... I've done it a bit tricky... I added a new input serverValue which is equal to servers response value and listen to it in directive.

But I think it's a bad way.

Maybe there are any better ways to populate input, listen for changes of ngModel and format it?

You can check my sandbox here: https://codesandbox.io/s/18qlqny42q to get a clear vision of what I try to do...

You can use pipe to format the input value. Something like this

<input type="text" (ngModel)="model" [value]="text | pipe" />

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