有没有办法做这样的事情:
<div [innerHTML]="content" (innerHTMLchange)="contentInit()"></div>
在我的代码中,我有一个变量 content
,它从从我的 Express 服务器获取字符串的服务中更新。当网站加载时,内容变量被设置,innerHTML 被更新。现在我有一个 javascript 库,需要对添加到 insideHTML 的字符串进行调用。我当前遇到的问题是 contentInit()
在 HTML 更新之前被调用。
constructor(private service: StringService) {
this.service.getString().subscribe((string) => {
this.content = string;
this.contentInit(); // called before innerHTML changes
});
}
contentInit: void {
var innerHTMLDiv = document.getElementById("innerHTML-div");
//do stuff
}
如果模板可以在innerHTML更改时调用contentInit()
,这应该可以解决我的问题,因为innerHTML将被启动并且它可以连接到元素。
最佳答案
只需显式调用更改检测,而不是等待 Angular 运行下一个周期:
constructor(private service: StringService, cdRef:ChangeDetectorRef) {
this.service.getString().subscribe((string) => {
this.content = string;
cdRef.detectChanges(); // after that the DOM is updated
this.contentInit(); // called before innerHTML changes
});
}
关于javascript - Angular 2 innerHTML更改事件绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43129846/