0

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...

brabertaser19
  • 5,678
  • 16
  • 78
  • 184

1 Answers1

0

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

<input type="text" (ngModel)="model" [value]="text | pipe" />
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27