【问题标题】:Reading components inside an Angular4 template / directive在 Angular4 模板/指令中读取组件
【发布时间】:2017-12-26 09:57:21
【问题描述】:

我正在研究一个网格组件,它主要由三件事组成,其中一些 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 的副作用?

感谢您的宝贵时间!

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    我设法通过将容器包装在my-row 组件而不是ng-container 中来解决此问题。像这样我可以直接访问组件。但是仍然使用该指令来创建上下文变量。

    【讨论】:

      【解决方案2】:

      你可以做的是标记第一行中的列

       <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>;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-13
        • 2018-06-13
        • 2020-09-05
        • 1970-01-01
        相关资源
        最近更新 更多