Angular借助指令传递模板

上一篇中使用@Host() @Optional() public hc: HelloComponent感觉不够优雅,也不符合正常数据传递流程。下面是改造后的实现逻辑。在HelloComponent中使用ContentChildren获取所有HelloDirective。
@Component({
selector: ‘hs-hello’,
template: `
<div>
<ng-container *ngFor=”let helloDirective of helloTemplates”>
<p>this is hello-for</p>
<ng-container *ngTemplateOutlet=”helloDirective.template”></ng-container>
</ng-container>
</div>
`
})
export class HelloComponent {
@ContentChildren(HelloDirective) helloTemplates: QueryList<HelloDirective>;
}
HelloDirective中将template向外暴露,借助指令传递TemplateRef,同时指令也起到了分类模板的作用
@Directive({
selector: ‘[hsHello]’
})
export class HelloDirective {

constructor(
public template: TemplateRef<any>
) {}
}
示例

<hs-hello>
<ng-template hsHello>
<p>this is hello-1</p>
</ng-template>

<ng-template hsHello>
<p>this is hello-2</p>
</ng-template>

<ng-template hsHello>
<p>this is hello-3</p>
</ng-template>
</hs-hello>

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理