Ben*_*cot 4 typescript transclusion angular2-ngcontent angular
我正在构建一个步进器并使用“嵌入”ng-content来动态抓取section步进器标签内的元素。stepper.component 视图的工作方式如下:
<ng-content select=".one"></ng-content>
<ng-content select=".two"></ng-content>
<ng-content select=".three"></ng-content>
Run Code Online (Sandbox Code Playgroud)
组件用法如下所示:
<stepper>
<section class="one">content here<section>
<section class="two">content here<section>
<section class="three">content here<section>
</stepper>
Run Code Online (Sandbox Code Playgroud)
但是,我想通过自动识别部分元素来使其动态化:
<ng-content *ngFor="let section of sections; index as i;" select="['section:nth-child(' + i + ')']"></ng-content>
Run Code Online (Sandbox Code Playgroud)
我怎样才能:
select以增量方式定位它们?我会创建一个指令,如:
@Directive({
selector: '[stepper-section]'
})
export class StepperSectionDirective {}
Run Code Online (Sandbox Code Playgroud)
然后stepper-section为每个部分添加属性:
<stepper>
<section stepper-section>content here<section>
<section stepper-section>content here<section>
<section stepper-section>content here<section>
</stepper>
Run Code Online (Sandbox Code Playgroud)
最后使用@ContentChildren装饰器查询所有部分:
@ContentChildren(StepperSectionDirective) sections: QueryList<StepperSectionDirective>;
Run Code Online (Sandbox Code Playgroud)
如果你想遍历内容并动态呈现它,你可以ng-template用ngTemplateOutletStepperComponent包裹你的孩子并使用指令来呈现它们:
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>
Run Code Online (Sandbox Code Playgroud)
stepper-section.directive.ts
@Directive({
selector: '[stepper-section]'
})
export class StepperSectionDirective {
hidden = false;
constructor(public templateRef: TemplateRef<any>) {}
}
Run Code Online (Sandbox Code Playgroud)
stepper.component.ts
@ContentChildren(StepperSectionDirective) sectionDirs: QueryList<StepperSectionDirective>;
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
这两种方法之间的区别在于,在第一种情况下,所有子内容都被渲染,我们只操作display: none我们想要隐藏的那些步骤。
在第二种方法中,我们可以更好地控制要渲染的内容,并且在特定时间只渲染一个步骤。
| 归档时间: |
|
| 查看次数: |
673 次 |
| 最近记录: |