2
Hi, I made a directive on Angular 2
to put masks on some fields, one of them the zip code. It works right, the only thing I could not do is that when loading the data in the fields of the screen the value is with the mask, it only works when the focus is in the field that has the directive.
I have tried to put several events on host, but none worked, I have tried to use change
, input
, but none of it worked.
Below follows the code HTML
with the input
which has the directive, the name of the directive is 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>
Now down with the directive code:
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);
}
}