вы можете внедрить "NgControl" внутри вашей директивы и затем присоединить к valueChanges, как это
@Directive({
selector: '[testDirective]'
})
export class TestDirective implements AfterViewInit{
constructor(private el: ElementRef,private ngControl:NgControl) {
this.listenToChanges();
}
private listenToChanges(){
this.ngControl.valueChanges.subscribe(()=>{
this.setCustomAttribute(); })
}
@HostListener('change') onChange() {
this.setCustomAttribute();
}
@HostListener('input') inputEvent() {
console.log("i am in input event");
//input event is not working either
}
private setCustomAttribute(){
if(this.el.nativeElement.value==null||this.el.nativeElement.value==""){
this.el.nativeElement.setAttribute("custom-attribute", "false");
}else{
this.el.nativeElement.setAttribute("custom-attribute", "true")
}
}
}
<input testDirective name="somefield" required type="text" [(ngModel)]="object.somefield">
и он автоматически отписывается, а директива будет уничтожена