0

I made some mask directives in Angular 2, one of them is for zip code. It mostly works but when loading the data in HTML, it only works when the focus is on the input that has the directive. I've tried putting various events in host, but none worked. I tried to use change, input, but none worked.

HTML:

input has the directive (directive name: cep)

<div class="col-sm-4">
        <div class="form-group fg-line">
            <label for="cep">CEP</label>
            <input type="text" class="form-control input-sm" id="cep" placeholder="CEP" required [(ngModel)]="empresa.Cep" borda-animada
                cep maxlength="9" ngControl="cep" #cep="ngForm">
        </div>
    </div>

Directive:

import {Directive} from '@angular/core';
import {NgModel} from '@angular/common';
import {Mascaras} from '../core/mascaras'

@Directive({
    selector: '[ngModel][cep]',
    providers: [NgModel],
    host: {
        '(blur)': 'onInputChange($event)',
        '(input)': 'onInputChange($event)'
    }
})
export class CepDirective {
    modelValue: string;
    viewValue: string;

constructor(public model: NgModel) {}

onInputChange(event) {
  console.log('teste ngmodelchange');

  //event é o evento html que é disparado no evento blur
  //por isso precisa pegar o target.value.
  var newValue = Mascaras.cep(event.target.value);
  this.model.valueAccessor.writeValue(newValue);       
  }
}
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Edmar Munhoz
  • 221
  • 1
  • 4
  • 12

1 Answers1

0

If you provide NgModel in the directive, it gets a new instance injected instead of the existing one.

This line needs to be removed:

providers: [NgModel],

Input mask fields in Angular2 forms shows a full example.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567