1

I have 2 @components say and . Now, I have to load dynamically as innerHTML in say for e.g. as below

component-1.html

<div [innerHTML]="domEl | safeHtml"></div>

In the Angular2 component-1 class

import {
  Component,
  OnInit,
  ViewEncapsulation
} from '@angular/core';


@Component({  
  selector: 'component-1',

  templateUrl: './component-1.html',

  encapsulation: ViewEncapsulation.None
})
export class Component1 implements OnInit {    

  public ngOnInit() {
    this.domEl = '<component-2 data="1234"></component-2>'
  }
}

component-2 is already inject in app.module.ts file via declarations[]. Also safeHtml is the pipes used for safe HTML transformation.

Even then the problem is component-2 is not loading. Can anyone suggest how I can fix this?

Note:

  • if I include component-2 in component-1.html directly it will work. But we have a case where we cannot inject component-2 dynamically.
  • Stack is build on Angular2, TypeScript and Webpack.
Ashwin Hegde
  • 1,733
  • 4
  • 19
  • 49
  • 1
    Instead of loading innerHtml, use templates with ngIf or ngSwitch. – Fals Mar 16 '17 at 14:24
  • Cannot do that, In my case that will not work. – Ashwin Hegde Mar 17 '17 at 05:26
  • You can't inject component as html. Components are rendered from Shadow Dom to Real Dom. When you inject something using **innerHTML**, It's expected to be raw Html, not stuff thats need rendering pipeline. As I said before, you must use ngIf or ngSwitch – Fals Mar 17 '17 at 13:11

1 Answers1

1

Angular doesn't process HTML passed to [innerHTML]="..." except sanitization for security purposes. Bindings, components, directives, ... are not created, because as mentioned, Angular ignores the content. What you can do is to create a component at runtime like explained in Equivalent of $compile in Angular 2. AFAIR someone built a module that makes this easier but I don't remember details.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567