如果使用自定义指令输入某些文本,我试图将属性添加到输入字段。我可以在@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">
你可以在你的指令中注入“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">
它将自动取消订阅,而指令将被销毁
尝试ngAfterViewInit方法
ngAfterViewInit(): void {
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")
}
}