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.
3
  • 1
    Instead of loading innerHtml, use templates with ngIf or ngSwitch. Commented Mar 16, 2017 at 14:24
  • Cannot do that, In my case that will not work. Commented Mar 17, 2017 at 5: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 Commented Mar 17, 2017 at 13:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.