I made some mask directives in Angular 2, one of them is for zip code. It works just right, but not working when loading the data on view 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.
Below is the HTML code with the input that has the directive, the directive name 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, below 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);
}
}
Aucun commentaire:
Enregistrer un commentaire