angular - 如何遍历部分元素以使用 ng-content 进行项目
问题描述
我正在构建一个步进器并使用“嵌入”ng-content
来动态抓取section
步进器标签中的元素。stepper.component 视图的工作方式如下:
<ng-content select=".one"></ng-content>
<ng-content select=".two"></ng-content>
<ng-content select=".three"></ng-content>
组件用法如下所示:
<stepper>
<section class="one">content here<section>
<section class="two">content here<section>
<section class="three">content here<section>
</stepper>
但是,我想通过自动识别部分元素来使其动态化:
<ng-content *ngFor="let section of sections; index as i;" select="['section:nth-child(' + i + ')']"></ng-content>
我怎样才能:
- 获取可用于嵌入的部分元素的节点列表?
- 使用 ng-content
select
来逐步定位它们?
解决方案
我会创建一个指令,如:
@Directive({
selector: '[stepper-section]'
})
export class StepperSectionDirective {}
然后stepper-section
为每个部分添加属性:
<stepper>
<section stepper-section>content here<section>
<section stepper-section>content here<section>
<section stepper-section>content here<section>
</stepper>
最后使用@ContentChildren
装饰器查询所有部分:
@ContentChildren(StepperSectionDirective) sections: QueryList<StepperSectionDirective>;
如果你想遍历内容并动态渲染它,你可以用StepperComponent包装你的孩子ng-template
并使用指令来渲染它们:ngTemplateOutlet
html
<app-stepper>
<ng-template stepper-section>Content 1</ng-template>
<ng-template stepper-section>Content 2</ng-template>
<ng-template stepper-section>Content 3</ng-template>
</app-stepper>
stepper-section.directive.ts
@Directive({
selector: '[stepper-section]'
})
export class StepperSectionDirective {
hidden = false;
constructor(public templateRef: TemplateRef<any>) {}
}
stepper.component.ts
@ContentChildren(StepperSectionDirective) sectionDirs: QueryList<StepperSectionDirective>;
stepper.component.html
<button *ngFor="let section of sections; index as i;"
[class.enabled]="activeSection === i" (click)="goTo(i)">
Step {{ i + 1 }}
</button>
<div class="content">
<ng-container *ngFor="let section of sections">
<ng-template *ngIf="!section.hidden"
[ngTemplateOutlet]="section.templateRef"></ng-template>
</ng-container>
</div>
这两种方法的区别在于,在第一种情况下,所有子内容都被渲染,我们只操作display: none
我们想要隐藏的那些步骤。
在第二种方法中,我们可以更好地控制要渲染的内容,并且在特定时间只渲染一个步骤。
推荐阅读
- python - 包含列子集的 CSV
- mysql - MYSQL 由于 Locking 导致性能下降
- python - Tensorflow:在 tf.data.Dataset 中拆分字符串的奇怪行为
- yii2 - 控制器中的 Yii2 更新查询不起作用
- r - R system2 并行运行不同的脚本
- asp.net-core-mvc - 如何在 MVC5 删除帖子中显示错误消息。已搜索但在删除上找不到任何内容
- java - 如何从位于 RecyclerView 内部的 ImageButton 启动另一个活动?
- android - Flutter - 根据 Android 产品风格设置目标文件
- c# - 如何使用 JSON.Net 遍历 JObject 键的 JProperties
- aframe - Aframe Physics 组件:沿路径反弹