你必须使用:this.zone.runOutsideAngular
我附上了示例来说明您在组件内部有角度和事件绑定的按钮。如我的示例所示,不要忘记取消绑定您的事件 onDestroy。
this.zone.runOutsideAngular(() => {
document.querySelector('#btn').addEventListener('click', () => {
this.foo();
});
});
https://stackblitz.com/edit/angular-xtkw3z?file=app%2Fapp.component.ts
更新1:
我创建了专门用于绑定按钮上的单击事件的自定义指令。
我删除了 DOMSanitizer,因为我们自动添加了 Event.stopPropagation()。所以你必须自己控制字符串是否安全。
@Directive({
selector: '[profil]'
})
export class UserProfilDirective implements OnInit, AfterViewInit {
@Input('profil') html: string;
constructor(
private el: ElementRef,
private zone: NgZone,
private renderer: Renderer2
) {
}
ngOnInit() {
//Take your html and add it as child html if current directive instance.
this.el.nativeElement.innerHTML = this.html;
}
ngAfterViewInit() {
//Out of angular.
this.zone.runOutsideAngular(() => {
// For each .profil of current instance.
[].forEach.call(this.el.nativeElement.querySelectorAll('.profil'), (el:Element, index: number) => {
//Ask rendering to add onClick event.
this.renderer.listen(el, 'click', (e) => {
//Do what ever you want with data profil such as output Event
console.log(e.srcElement.getAttribute('data-profile'));
});
});
});
}
}
源代码在这里:
https ://stackblitz.com/edit/angular-cua3is?file=app/app.component.ts