Search code examples
angulartypescriptangular-directive

Angular 4 Input Directive onSave


I made a directive for a two-way binded input, on the event onKeyPress I give it the columbian format. e.g. I input:

1000.25

And the directive change it to:

1.000,25

Now, before binding the value to my model I want to remove the given format, my questions are:

  • Is there a way I can fire an event in the input directive when is being submitted (by a submit button)?
  • And if it is possible, how? I really couldn't find anything alike, thanks in advance.

Solution

  • You can access NgForm from you directive via DI. In that form you have ngSubmit observable. It emits values on form submit.

    import { NgForm } from '@angular/forms';
    
    constructor(form: NgForm) {
      this.form.ngSubmit.subscribe(<do stuff>)
    }
    

    But are you sure you really need to physically modify model value? Probably you just need to modify VIEW value. Perhaps you need something like $formatters from AngularJS. You can research more reading this article