Angular中ngTemplateOutlet和指令结合使用

11次阅读

共计 851 个字符,预计需要花费 3 分钟才能阅读完成。

在 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>

正文完
 0