Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 showing null in IE

Tags:

angular

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!

like image 278
Silver Avatar asked May 07 '26 20:05

Silver


2 Answers

Correct Syntax in Angular2 should be

<div *ngIf="heading" [innerHTML]="heading"></div>
like image 181
Parth Ghiya Avatar answered May 10 '26 16:05

Parth Ghiya


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);
    };
  }
like image 21
William Neely Avatar answered May 10 '26 17:05

William Neely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!