[英]Reading components inside an Angular4 template / directive
我正在研究一個網格組件,該組件主要由三部分組成:一些GridComponent組件需要一個數組數據源,一個RowItem指令僅負責為行創建上下文,而ColumnComponent則是該組件的定義。列的內容。
簡而言之,組件的用法如下所示:
<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>
現在,我的列定義如下:
<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>
我現在遇到的問題與呈現列名有關。 我正在嘗試使用下面的ContentChildren收集名稱
@ContentChildren(ColumnComponent)
public columns: QueryList<ColumnComponent>;
但是,由於網格中有* 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>;
我設法通過將容器包裝在my-row
組件而不是ng-container
來解決此問題。 這樣,我可以直接訪問組件。 但是仍然使用該指令創建上下文變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.