【发布时间】:2019-04-19 11:52:42
【问题描述】:
如果使用自定义指令输入了某些文本,我正在尝试将属性添加到输入字段。我可以在 @HostListener('change') 事件中做到这一点。 这对于创建页面来说非常好,但是在编辑页面中,数据是通过 NgModel 异步加载和绑定的,所以我找不到任何这样做的事件。任何帮助,将不胜感激。
@Directive({
selector: '[testDirective]'
})
export class TestDirective implements AfterViewInit{
constructor(private el: ElementRef) { }
@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">
【问题讨论】:
-
试试
ngOnInit()