Angular中ngTemplateOutlet和指令结合使用

本文深入探讨了kendo Grid组件中kendoGridCellTemplate指令的实现原理,通过示例展示了如何在Angular环境中使用自定义指令与组件进行交互,特别关注了如何利用ngTemplateOutlet和ContentChild来实现动态模板加载。
在kendo的Grid组件中,可以看到有大量类似kendoGridCellTemplate这样的指令。 那么这些指令是怎样实现的。
    <kendo-grid ...>
        <kendo-grid-column ...>
            <ng-template kendoGridCellTemplate let-dataItem let-i="index">
                ....
            </ng-template>
        </kendo-grid-column>
    </kendo-grid>
  • 下面是实现 在HelloComponent组件中使用 helloTemplate指令的代码
@Component({
    selector: 'hs-hello',
    template: `
        <div>
            ...
            <ng-container *ngTemplateOutlet="ct; context:ctx"></ng-container>
        </div>

    `
})
export class HelloComponent {

    ctx = {
        $implicit: 'aaa',
        hello: 'bbb'
    };

    @ContentChild('cellTemplate') ct: TemplateRef<any>;

    constructor() {}

}
    
@Directive({
    selector: '[helloTemplate]',
})
export class HelloTemplateDirective implements OnInit {

    constructor(
        private template: TemplateRef<any>,
        @Host() @Optional() public hc: HelloComponent
    ) {

    }

    ngOnInit() {
        this.hc.headerTemplate = this.template;
    }
}
    <hs-hello>
        <ng-template helloTemplate let-dataItem let-hello="hello">
            <p>{{dataItem}} -- {{hello}}</p>
        </ng-template>
    </hs-hello>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值