首页 > 解决方案 > 如何通过 HTML 将字符串传递给 ng-template?

问题描述

假设我有一个像这样的 ng-template:

<ng-template #templateRef>
 <button
  (click)="testClick()"
  Click me
 </button>
 <a
  I'm a link
 </a>
</ng-template>

然后我想在我的html模板中使用它

<ng-container
        [ngTemplateOutlet]="templateRef"
        [ngTemplateOutletContext]="asdf"
>
</ng-container>

有什么方法可以让我将一个额外的变量传递给模板,以便根据我在 html 中使用模板的位置,我可以传递一个不同的字符串,我可以使用该字符串通过属性绑定设置自定义指令的值?IE 我真的希望最终结果是

 <button
  (click)="testClick()"
  [customLocation]="top"
  Click me
 </button>
 <a
  [customLocation]="top"
  I'm a link
 >
 </a>

 <button
  (click)="testClick()"
  [customLocation]="bottom"
  Click me
 </button>
 <a
  [customLocation]="bottom"
  I'm a link
 >
 </a>

所以当我使用模板时

    <ng-container
            [ngTemplateOutlet]="templateRef"
            [ngTemplateOutletContext]="asdf"
    >
    </ng-container>

我只想保留当前存在的所有内容,并将另一个变量传递到容器中,该变量将作为 customLocation 的值。这可以做到吗?任何帮助表示赞赏

标签: htmlangular

解决方案


模板有一个上下文。在这里,我们创建了一个名为location感谢语法的模板变量let-location。该变量将绑定到上下文的 $implicit 属性。

<ng-template #templateRef let-location>
 <button
  [customLocation]="location"
 </button>
</ng-template>

<ng-container
  [ngTemplateOutlet]="templateRef"
  [ngTemplateOutletContext]="{$implicit: 'top'}"
>
</ng-container>

请注意,通过命名模板变量是可能的。它在https://angular.io/api/common/NgTemplateOutlet中有解释。


推荐阅读