我试图在单击按钮时生成一个动态div,其中该动态div中包含一个自定义指令属性。但是在呈现为DOM之后,自定义指令不适用于动态创建的元素。
我已经尝试过https://stackblitz.com/edit/angular-comp-interact-asd
comp1.component.ts
let tmpdta = "<p appChangedta >Dynamic div</p>";
this.dynamicDiv = this.sanitizer.bypassSecurityTrustHtml(tmpdta);
}
comp1.component.html
<div [innerHtml]="dynamicDiv"></div>
changedata.directive.ts
selector: '[appChangedta]'
})
export class ChangedtaDirective implements OnInit {
constructor(private elemref: ElementRef, private renderer: Renderer2) { }
ngOnInit() {
}
@HostListener('mouseenter') mouseenter(eventData: Event){
this.elemref.nativeElement.innerText = "Mouse Enter";
this.renderer.setStyle(this.elemref.nativeElement, 'background-color', 'green');
}
@HostListener('mouseleave') mouseleave(eventData: Event){
this.elemref.nativeElement.innerText = "Mouse Leave";
this.renderer.setStyle(this.elemref.nativeElement, 'background-color', 'deepskyblue');
}
}