It's a question large dicuss. I feel that the better bet is use a directive
import { NgControl } from '@angular/forms';
@Directive({
selector: '[onblur]',
})
export class BlurFormatDirective implements OnInit {
@Input('onblur') transform: (string) => string | null;
@HostListener('blur') onBlur() {
if (this.transform && this.control)
this.el.nativeElement.value = this.transform(this.control.value);
}
@HostListener('focus') onFocus() {
if (this.transform && this.control)
this.el.nativeElement.value = this.control.value?
this.control.value:'';
}
constructor(
private el: ElementRef,
@Optional() @Host() private control: NgControl
) {}
ngOnInit() {
setTimeout(() => {
this.onBlur()
});
}
}
Now we can use some like
<input [onblur]="transform" [(ngModel)]="name">
where
name = 'Angular ' + VERSION.major;
transform(value:string)
{
//e.g. transform a string
return value.split('').map((x,i)=>i%2?x:'*').join('');
//or
return formatCurrency(+value,'en-GB',"$")
}
see stackblitz
NOTE: This directive only work for template driven forms or Reactive Forms