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);
}
}