Angular借助指令传递模板

发布时间:2019-06-25 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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>

脚本宝典总结

以上是脚本宝典为你收集整理的Angular借助指令传递模板全部内容,希望文章能够帮你解决Angular借助指令传递模板所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。