首页 文章

具有嵌套组件的角动态组件

提问于
浏览
1

我正在构建一个基本上是电子书的应用程序 . 每个页面都具有相同的外部格式,其中包含使用HTML和自定义组件定义的唯一内容 .

外页定义为:

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

page-content 有模板

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

然后将其中一个 page-content 元素定义为

<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>

我一直在关注https://angular.io/guide/dynamic-component-loader的指南,我想使用本指南动态加载页面内容 .

如何定义 page-content 组件,以便将内部内容映射到 ng-content 元素?应该使用 ng-template 吗?

有没有人做过类似的事情,所有的页面内容元素都存储在assets目录中并动态加载?

非常感谢您的帮助 .

1 回答

  • 1

    将内容传递为 projectableNodes 应该这样做

    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]});
    

    另见https://stackoverflow.com/a/40323785/217408

相关问题