例如:
我想要bulid表组件AppTableComponent:
<app-table [dataSource]="dataSource" [columns]="columns"> <ng-container tableColumnDef="actions"> <a routerLink="/model/edit/{{item.id}}" routerLinkActive="active">Edit</a> <a routerLink="/model/delete/{{item.id}}" routerLinkActive="active">Delete</a> </ng-container> <ng-container tableColumnDef="isActive"> <div [ngClass]="{cercl:true,'is-active':item.is_active}"> </div> </ng-container> </app-table>
dataSource是数据数组,如Model []或Person []或Car []. columns是一个字符串数组,如[‘id’,’isActive’,’name’,’actions’].它应该包含dataSource行的名称或附加列名称.
我知道如何使用ng-content,但这不是一个很小的例子.区别是我应该在一些地方使用部分内容.也许我应该使用ng-contet,但我不知道什么.
我确信我的目标是可行的,因为Angular材料表的工作如下:
<mat-table #table [dataSource]="dataSource"> <ng-container matColumnDef="position"></ng-container> <ng-container matColumnDef="weight"></ng-container> </mat-table>
请不要建议我使用Angular材料表组件.我不需要桌子.我只想学习一些新东西.
解决方法
<table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="position"> <th mat-header-cell *matHeaderCellDef> No. </th> <td mat-cell *matCellDef="let element"> {{element.position}} </td> </ng-container>
你可以说没有任何嵌入式视图,但让我们看看上面模板的扩展版本:
<table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="position"> <ng-template matHeaderCellDef> <th mat-header-cell> No. </th> </ng-template> <ng-template matCellDef let-element="$implicit"> <td mat-cell> {{element.position}} </td> </ng-template> </ng-container>
我们可以注意到< ng-template matHeaderCellDef>这里可以通过使用ContentChild获得.
Angular材料团队为此类模板创建专用指令https://github.com/angular/material2/blob/f2c7205d6608d36a2016d90090be2a78d4f3233e/src/lib/table/cell.ts#L32,该模板保留对嵌入式模板https://github.com/angular/material2/blob/676ce3b285718d2ee19ad6ae5702917566167641/src/cdk/table/cell.ts#L34的引用
材料表组件具有以下模板:
<ng-container headerRowOutlet></ng-container> <ng-container rowOutlet></ng-container> <ng-container footerRowOutlet></ng-container>
还有指令 – 助手,如:
@Directive({selector: '[headerRowOutlet]'}) export class HeaderRowOutlet implements RowOutlet { constructor(public viewContainer: ViewContainerRef,public elementRef: ElementRef) { } }
这样我们就可以使用低级api来创建基于嵌入式模板的元素,例如ViewContainerRef.createEmbeddedView(templateRef),但是可以在这里找到简单的实现:
> How to render multiple ng-content inside an ngFor loop using Angular 4?