首页 > 解决方案 > 如何为响应式表单设置模板上下文?

问题描述

我在组件中有一组FormGroup称为fgList初始化的。像这样:

const fgList = [
    new FormGroup({ /* ... */),
    new FormGroup({ /* ... */)
];

对于模板,我想使用*ngForng-template关联,可以吗?

<div *ngFor="let fg of fgList">
    <ng-container *ngTemplateOutlet="colorText; context: fg"></ng-container>
</div>

<ng-template #colorText>
    <span class="red">{{ fg.get('name').value }}</div>
</ng-template>

它一直说无法读取 undefined 的属性'get'。我可以知道如何fg在模板中传递和使用它吗?

标签: angular

解决方案


因为你的*ngFor如果关闭。

尝试使用以下代码:

<div *ngFor="let fg of fgList">
    <ng-container *ngTemplateOutlet="colorText; context: fg"></ng-container>


<ng-template #colorText>
    <span class="red">{{ fg.get('name').value }}</div>
</ng-template>
</div>


推荐阅读