繁体   English   中英

访问组件内的模板变量

[英]Access template variable inside component

我遇到了 ng-template 的问题。

我们通过 ngTemplateOutletContext 在表格组件中传递一些参数,如下所示。 我们根据其中包含的数据类型为单元格使用不同的渲染器。 注意 cellvalue 参数,因为它是我需要的。

<ng-container *ngIf="useCellRenderer(column, row)">
   <ng-template [ngTemplateOutlet]="column.renderer.templateref" [ngTemplateOutletContext]="{ cellvalue: row[column.attr], rowvalue:row }">
   </ng-template>
</ng-container>

负责渲染的组件的模板如下所示:

<ng-template #templateRef let-cellvalue="cellvalue" let-rowvalue="rowvalue">
  {{ getTraslateValue(cellvalue)}}
</ng-template>

模板能够访问 cellvalue 参数并正确调用该函数,但我想从组件的 TS 访问相同的参数并且似乎无法做到这一点。

到目前为止我尝试过的内容与以下代码段一致

@ViewChild('templateRef', { read: TemplateRef })
  public templateref: TemplateRef<any>;

  ngAfterViewInit() {
    console.log('ngAfterViewInit', this.templateref.elementRef);
  }

但是在console.log中找不到cellvalue

提前致谢!

所以@SebOlens 用他的话引导我找到了解决方案。 我结束了使用 exportAs 创建指令。 该指令如下:

TS

@Directive({ selector: '[exposeVariable]', exportAs: 'exposed' })
export class ExposeVariableDirective {
  @Input() variablesToExpose: any;
  }
}

例如,它可以通过以下方式在模板中使用:

HTML

<ng-template #templateRef let-cellvalue="cellvalue" let-rowvalue="rowvalue">
  <div exposeVariable [variablesToExpose]="{cellValue: cellvalue}" #exposedRef="exposed">
    {{ getTraslateValue(cellvalue)}}
  </div>
</ng-template>

并且可以从组件访问单元格值:

TS

@ViewChild('exposedRef') public directiveExposed: any;

在我的情况下,指令在组件的AfterViewInit之后初始化,因此如果您尝试初始化某些内容,您将不得不观察ViewChild变量的值,或者在我的情况下,我做了一个使用ngIf和公开变量激活的组件来自模板,所以我可以使用新组件中的钩子。

再次感谢@SebOlens :)

好的,所以这不是一个答案,只是一个建议,所以如果它不起作用,请不要减去它。

你有没有尝试过这样的事情?

html

<ng-template #cellValue="cellvalue" let-cellvalue="cellvalue" let-rowvalue="rowvalue">
  {{ getTraslateValue(cellvalue)}}
</ng-template>

ts

@ViewChild('cellValue') public cellValue: any;

我不确定它是否会起作用,因为像#cellValue="cellvalue"exportAs于在装饰器中有exportAs描述的指令

这是行不通的:

@ViewChild('templateRef', { read: TemplateRef })
  public templateref: TemplateRef<any>;

因为它引用了模板本身而不是 dom 的生成部分。 也许尝试引用模板生成的 dom 部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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