我正在编写一个可重用的Angular 2组件来检索和显示表中的数据,并进行服务器端排序,过滤和搜索。我希望表中的每一行都有一个额外的列,其中包含使用ng-context标记的泛型html,我可以这样做。
最常见的情况是使用可以使用构造每行的数据执行操作的按钮(例如,导航到条目的特定页面,或删除条目),但似乎没有是一种将对象传递给组件的ContentChildren的方法。我也许可以通过直接的DOM操作和检查来实现这一点,但这对于可重用性来说非常糟糕和不好。
我并不真正关心任何具体的实现方法,只要它:
我正在使用打字稿,因此首选类型安全的解决方案,但如果需要,我很乐意忽略类型系统。
我正在使用的表组件(my-table)看起来像
<my-table /* some properties */>
<button class="row-button" type="button" (click)="navigate(/* context */)">Navigate</button>
</my-table>
其模板使用ng-content,如下所示:
// table html
<tr *ngFor="let row of rows">
<td *ngFor="let column of row.columns">{{column}}</td>
<td>
<ng-content select=".row-button"></ng-content>
</td>
</tr>
// more table html
如果我可以将参数传递给按钮元素可以使用的ng-content,那就足够了。
答案 0 :(得分:5)
一种方法是模板变量,允许您显式引用父:
<my-table #myTable>
<button [context]="myTable.context">
</my-table>
据我所知,有计划让这更灵活。我想这就是这个问题https://github.com/angular/angular/issues/8563
答案 1 :(得分:4)
如果您不严格使用ng-content,ng-template
可以做到:
<my-table [rowButtonTemplate]="buttonTemplate" /* some properties */>
<ng-template #buttonTemplate let-column>
<button class="row-button" type="button" (click)="navigate(column.context)">Navigate</button>
</ng-template>
</my-table>
然后在表格内
// table ts
@Input()
rowButtonTemplate: TemplateRef;
// table html
<tr *ngFor="let row of rows">
<td *ngFor="let column of row.columns">{{column}}</td>
<td>
<ng-container *ngTemplateOutlet="rowButtonTemplate; context: { $implicit: column, index: index }"></ng-container>
</td>
</tr>
// more table html