[英]Angular2 showing null in IE
I have the following in an Angular2 component: 我在Angular2组件中有以下内容:
<div ng-if="heading" [innerHTML]="heading"></div>
Chrome & Safari work fine - but IE is showing null
in the DIV. Chrome和Safari工作正常 - 但是IE在DIV中显示为
null
。 I have no idea why... heading is undefined
, double-checked! 我不知道为什么......标题
undefined
,双重检查!
Angular2中的正确语法应该是
<div *ngIf="heading" [innerHTML]="heading"></div>
For those who don't like the fact that you have to do ngIf whenever the innerHTML may be undefined, here's a solution to resolve this across your app: 对于那些不喜欢每当innerHTML可能未定义时必须执行ngIf这一事实的人,这里有一个解决方案来解决你的应用程序:
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) || '';
};
}
I place this in the app.module constructor. 我把它放在app.module构造函数中。
You may ask, "why such a hacky approach?" 你可能会问,“为什么这么黑客的做法?” That's largely because DomSanitizer is an interface acting as a class.
这主要是因为DomSanitizer是一个充当类的接口。 The real sanitization happens in the DomSanitizerImpl class that isn't publicly exposed.
真正的清理发生在未公开暴露的DomSanitizerImpl类中。
EDIT 6/18/19 Here's one for textContent as its done differently but produces undefined in IE 编辑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);
};
}
它是*ngIf
<div *ngIf="heading" [innerHTML]="heading"></div>
Angular2 NgIf syntax: Angular2 NgIf语法:
<div *ngIf="condition">...</div>
<div template="ngIf condition">...</div>
<template [ngIf]="condition"><div>...</div></template>
Example: 例:
<div *ngIf="errorCount > 0" class="error">
<!-- Error message displayed when the errorCount property in the current context is greater than 0. -->
{{errorCount}} errors detected
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.