Cor*_*ant 5 components typescript angular
我正在编写一个可重用的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>
Run Code Online (Sandbox Code Playgroud)
其模板使用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
Run Code Online (Sandbox Code Playgroud)
如果我可以将参数传递给ng-content,那么按钮元素可以使用这个参数就足够了.
如果你对使用 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>
Run Code Online (Sandbox Code Playgroud)
然后在表内:
// 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
Run Code Online (Sandbox Code Playgroud)
一种方法是模板变量,允许您显式引用父:
<my-table #myTable>
<button [context]="myTable.context">
</my-table>
Run Code Online (Sandbox Code Playgroud)
据我所知,有计划使这更灵活.我想是这个问题https://github.com/angular/angular/issues/8563
| 归档时间: |
|
| 查看次数: |
5296 次 |
| 最近记录: |