Angular Pipe-访问组件实例

时间:2019-05-07 10:15:19

标签: angular

在我的TableComponent内,我正在维护一个字典来表示选中的行。

private checkedRows: Dictionary<boolean> = {}; // { [id: string]: boolean }

然后我有一种在模板内部使用的方法

isRowCheckDisabled(rowId: string): boolean {
   return (
      !this.checkedRows[rowId] && this.getCheckedRowsCount() >= this.selectionOpt.limit
   );
}

getCheckedRowsCount(): number {
   return Object.keys(this.checkedRows).length;
}

模板:

<td 
  ...
  [nzDisabled]="isRowCheckDisabled(row.id)"
  ...
</td>

我想将此逻辑移至 pure (也许?)Pipe中。
但是,在没有直接访问组件字段的情况下,我将必须使用签名来实现它,例如

transform(
    rowId: string, 
    checkedRows: Dictionary<boolean>,
    selectionOpt: SelectionOpt | undefined): boolean
) { ... } 

并像

一样使用它
[nzDisabled]="row.id | checked: checkedRows:selectionOpt"

哪个不是真的“好”。

问题是,管道可以访问当前Component上下文及其字段吗?
有一个更好的方法吗?我应该坚持使用这种方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用:

constructor(cdRef: ChangeDetectorRef) {
    (cdRef as EmbeddedViewRef<Type<any>>).context
}
相关问题