1

I am building an app that is basically a e-book. Each page has the same outer formatting with unique content which is defined using HTML and custom components.

The outer page is defined as:

<header></header>
  <outerborder>
    <page-content></page-content>
  </outerborder>
<footer><footer>

page-content has the template of

<div>
  <p class="title">{{title}}</p>
  <ng-content></ng-content>
  <p class="pageno">{{pageno}}</p
</div>

one of the page-content elements is then defined as

<page-content title="title1" pageno="6">
  <p>introduction</p>
  <custom-comp1>more text</custom-comp1>
  <custom-comp2>and more text</custom-comp2>
  <button>button text</button>
</page-content>

I have been following the guide at https://angular.io/guide/dynamic-component-loader and I want to use this guide to load page-content dynamically.

How can the page-content component be defined such that the inner contents are mapped into the ng-content element? Should ng-template be used instead?

Has any one done anything similar where all the page-content elements are stored in the assets directory and loaded at dynamically?

Thank you very much for any assistance.

phil magnuson
  • 71
  • 1
  • 9

1 Answers1

0

Passing the content as projectableNodes should do that

let content = document.createElement('div');
content.innerHTML = `
  <p>introduction</p>
  <custom-comp1>more text</custom-comp1>
  <custom-comp2>and more text</custom-comp2>
  <button>button text</button>
`;

let componentRef = viewContainerRef.createComponent(componentFactory, {projectableNodes: [content]});

See also https://stackoverflow.com/a/40323785/217408

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    This also could be helpful https://stackoverflow.com/questions/44284026/creating-a-angular2-component-with-ng-content-dynamically/44289996#44289996 – yurzui Feb 16 '18 at 18:44
  • In the angular example at https://angular.io/guide/dynamic-component-loader, the add components are defined using: `new AdItem(HeroProfileComponent, {name: 'Bombasto', bio: 'Brave as they come'})`. How can I define my `` to use this model? – phil magnuson Mar 06 '18 at 17:20
  • Sorry, I don't understand the question. There is no `new AdItem(...)` in the linked page. – Günter Zöchbauer Mar 06 '18 at 17:41
  • Gunter, thank you so much for looking at this. They don't have the full source on the page, its in the .zip download. This is an equivalent plunker https://embed.plnkr.co/ZM2wSc/. In the `loadComponent` function, values are assigned to the the various components. I'm not sure how to define my `` class so I can assign values to a property that gets into the `` in the template. Thanks again. – phil magnuson Mar 06 '18 at 22:49