14

I want to create a component myApp that will embed HTML from a property on the controller in its template. However, some of that HTML may include other component selectors.

import {InfoComponent} from ...
@Component({
    selector: 'myApp',
    template: `<div [innerHTML]='hData'></div>
               <myInfo></myInfo>`,
    directives: [InfoComponent]
})
export class AppComponent {
   hData = "<myInfo></myInfo>";
}

@Component({
   selector: 'myInfo',
   template: "<b>This is a test</b>"
})
export class InfoComponent {
}

In this example, I would expect to see This is a test displayed twice. However, it doesn't appear that the Angular2 engine picks up on the fact that the selector of the Component has been injected so the template never gets generated for the <myInfo></myInfo> selector that is add via the binding.

You can see a demo here.

Is there a way to get Angular2 to parse the selector in the same way it does with the selector that is added explicitly in the template?

1 Answer 1

4

There is no way to make [innerHtml]="..." instantiate Angular components or directives or establish any bindings.

The closest for this requirement is DynamicComponentLoader. (DynamicComponentLoader was removed a while ago) ViewContainerRef.createComponent()

See Angular 2 dynamic tabs with user-click chosen components for an example

Since RC.5 Angular2 sanitizes styles and HTML added through binding. See In RC.1 some styles can't be added using binding syntax for more details.

9
  • 1
    I think the DynamicComponentLoader is exactly what I'm looking for. Thanks so much.
    – RHarris
    Apr 4, 2016 at 17:44
  • 1
    But if it's not a component you're trying to load how does it work? If it's only a simple html string? Apr 5, 2016 at 9:30
  • 1
    @GünterZöchbauer I've been trying to implement the DynamicComponentLoader per your suggestion but ran into an issue where one of the loaded components requires a service. I've posted about it here stackoverflow.com/questions/36490509/…. Would you have any suggestions?
    – RHarris
    Apr 8, 2016 at 18:43
  • 1
    DynamicComponentLoader link is dead. Oct 15, 2016 at 3:41
  • 1
    I guess you need stackoverflow.com/questions/37076867/… Nov 28, 2016 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.