我正在尝试在Angular中创建一个包装器组件,该组件可以容纳任意数量的子代,然后逐项包装每个项目。最好完全动态地绑定任何额外的数据。
app-wrapper.component 应该工作像这样((仅处理包装程序的逻辑):
<div class="wrapper">
<div
class="child-wrapper"
*ngFor="let child of children"
>
<ng-content [select]="child"></ng-content>
</div>
</div>
并且使用app-wrapper ((处理项目的逻辑):
<app-wrapper>
<app-first-item></app-first-item>
<app-second-item></app-second-item>
...
<app-last-item></app-last-item>
</app-wrapper>
app-wrapper.component不能像这样工作,抛出错误:
错误:模板解析错误:由于它不是'ng-content'的已知属性。
请注意:div.wrapper和div.child-wrapper不能分开。
似乎有几种方法可以做到这一点。
1 /您可以将它们变成组件:
app-wrapper.component:
<div class="wrapper">
<div
class="child-wrapper"
*ngFor="let child of children"
>
<app-item [item]="child"></app-item>
</div>
</div>
并使用@Input创建ItemComponent以显示项目。
2 /您可以使用ngTemplateOutlet指令创建模板引用app-wrapper.component:
<div class="wrapper">
<div
class="child-wrapper"
*ngFor="let child of children"
>
<ng-container *ngTemplateOutlet="test; context: { child: child }"></ng-container>
</div>
</div>
<ng-template #test let-child="child">
<!-- here an item -->
</ng-template>
ng-content用于将内容注入元素内,如下所示:
在您的应用包装程序中:
<div class="wrapper">
<ng-content select="[child]"></ng-content>
</div>
以及当您调用组件时:
<app-wrapper>
<div child>element you want to put inside the "ng-content" </div>
</app-wrapper>