读取Angular4模板/指令内的组件
我正在开发一个网格组件,它主要由三部分组成,其中一些 GridComponent组件,接收数组数据源、RowItem指令(仅负责为行创建上下文)和ColumnComponent(列内容的定义) 简而言之,组件的用法如下所示:读取Angular4模板/指令内的组件,angular,typescript,Angular,Typescript,我正在开发一个网格组件,它主要由三部分组成,其中一些 GridComponent组件,接收数组数据源、RowItem指令(仅负责为行创建上下文)和ColumnComponent(列内容的定义) 简而言之,组件的用法如下所示: <my-grid [data-source]="dataSource"> <ng-container *rowItem="let item"> <my-column column-header="Person">
<my-grid [data-source]="dataSource">
<ng-container *rowItem="let item">
<my-column column-header="Person">
{{item.name}}
</my-column>
<my-column column-header="Age">
{{item.age}}
</my-column>
<my-column column-header="Car">
{{item.car}}
</my-column>
</ng-container>
</my-grid>
{{item.name}
{{item.age}
{{item.car}
现在,我的列定义如下:
<ng-container *ngIf="someConditionHere">
<ng-content></ng-content>
</ng-container>
它将收集开发人员指定的内容并传递到网格,网格将负责呈现完整的控件,如下面的模板所示
<table>
<thead>
<tr>
<th *ngFor="let col of columns">
{{col.columnHeader}}
</th>
</tr>
</thead>
<tbody>
<tr class="core-grid-row" *ngFor="let row of dataSource">
<ng-template [ngTemplateOutlet]="rowItem" [ngOutletContext]="{$implicit: row}"></ng-template>
</tr>
</tbody>
</table>
{{col.columnHeader}}
我现在遇到的问题与呈现列名有关。我试图用下面的内容收集这些名字
@ContentChildren(ColumnComponent)
public columns: QueryList<ColumnComponent>;
@ContentChildren(ColumnPonent)
公共栏目:QueryList;
但是,由于网格中有*ngFor指令,因此我的ContentChildren查询将收集乘以行数的列,而不是仅收集第一行。有没有什么方法可以让我以干净整洁的方式收集列名而不受*ngFor的副作用影响
谢谢你的时间 您可以做的是标记第一行中的列
<tr class="core-grid-row" *ngFor="let row of dataSource; let i = index">
<ng-template [ngTemplateOutlet]="rowItem" [ngOutletContext]="{$implicit: row, 'i: i}"></ng-template>
</tr>
(我不太确定通过ngOutletContext传递索引的代码样式,…可能有点不同)
然后可以使用索引标记第一列:
<ng-container *ngIf="i == 0 && someConditionHere" #headerColumn>
<ng-content></ng-content>
</ng-container>
<ng-container *ngIf="i > 0 && someConditionHere">
<ng-content></ng-content>
</ng-container>
然后,您应该能够通过以下方式仅获取第一行列:
@ContentChildren(#headerColumn)
public columns: QueryList<ColumnComponent>;
@ContentChildren(#headerColumn)
公共栏目:QueryList;
我通过将容器包装在my row
组件中,而不是ng容器中,设法解决了这个问题。这样我就可以直接访问组件。但是,仍然使用该指令创建上下文变量