繁体   English   中英

读取Angular4模板/指令中的组件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM