I have the following in an Angular2 component:
<div ng-if="heading" [innerHTML]="heading"></div>
Chrome & Safari work fine - but IE is showing null in the DIV. I have no idea why... heading is undefined, double-checked!
Correct Syntax in Angular2 should be
<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:
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.
You may ask, "why such a hacky approach?" That's largely because DomSanitizer is an interface acting as a class. The real sanitization happens in the DomSanitizerImpl class that isn't publicly exposed.
EDIT 6/18/19 Here's one for textContent as its done differently but produces undefined in 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);
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With