I have created an attribute directive myOptional
meant to be used on inputs in a form, and its purpose is to indicate that certain fields are optional. This is done by adding a class to the input and then the optional text is shown using css pseudo element ::after
.
The "Optional" label is meant to be displayed only when the input's value is empty, and the focus is elsewhere.
So, when the directive is initialized, we add the class to the input
ngOnInit() {
this.addOptionalClass();
}
On focus, we remove the class and therefore, the Optional label
@HostListener('focus') onfocus() {
this.removeOptionalClass();
}
On blur, if the input's value is still empty, we shown the label
@HostListener('blur') onblur() {
if (this.isInputElement()) {
let inputValue = (<HTMLInputElement>this.el).value;
if (inputValue === '') this.addOptionalClass();
}
}
So far, so good. The problem occurs when the input's value is set by updating the control in the form. In that case, when the input's value is updated and not empty, I'd like to remove the class.
I assumed I'd be able to attach an event listener to the onchange
event, but the code below is not triggered at all. I even tried modifying the input's value using document.getElementBydId
as well, with no success.
@HostListener('change') onchange() {
console.log((<HTMLInputElement>this.el).value);
}
Hope I made myself clear. Any help would be greatly appreciated.
@Input
properties always should bepublic
. – Paraldehyde