我在Angular2组件中有以下内容:
<div ng-if="heading" [innerHTML]="heading"></div>
Chrome和Safari工作正常 - 但IE正在nullDIV中展示.我不知道为什么......标题是undefined,经过双重检查!
Angular2中的正确语法应该是
<div *ngIf="heading" [innerHTML]="heading"></div>
Run Code Online (Sandbox Code Playgroud)
对于那些不喜欢必须执行ngIf的事实的人,无论何时未定义innerHTML,以下是一种在您的应用程序中解决此问题的解决方案:
constructor(sanitize: DomSanitizer) {
// override the sanitize method so that it returns an empty string instead of null so that IE doesn't show "null" in the DOM
sanitize.sanitize = function(context: SecurityContext, value: SafeValue | string | null) {
return (sanitize as any).__proto__.sanitize.call((sanitize as any), context, value) || '';
};
}
Run Code Online (Sandbox Code Playgroud)
我将其放在app.module构造函数中。
您可能会问:“为什么要采用这种笨拙的方法?” 这主要是因为DomSanitizer是充当类的接口。真正的清理发生在未公开的DomSanitizerImpl类中。
编辑6/18/19这是一个针对textContent的方法,其处理方式不同,但在IE中产生未定义的内容
constructor(renderer: Renderer2) {
/**
* in IE, textContent = undefined gets put in the DOM as string, "undefined".
* this is to override that behavior. We would put this in app.module
* with the hack for DOM sanitization but in order to access the renderer,
* we need to be in a component
*/
const setProperty = (renderer as any).__proto__.setProperty;
(renderer as any).__proto__.setProperty = function(el: Element, name: string, value: string) {
if (name === 'textContent' && value === undefined) {
value = '';
}
setProperty.call(this, el, name, value);
};
}
Run Code Online (Sandbox Code Playgroud)