简体   繁体   English

ng-template中的动态数据

[英]Dynamic data in ng-template

I'm relatively new to Angular and struggling to figure out how to pass a string into a template. 我是Angular的新手,正在努力弄清楚如何将字符串传递到模板中。 I would like to create a reusable template (or component) that will display some instruction information on how to proceed with an action. 我想创建一个可重用的模板(或组件),该模板将显示一些有关如何进行操作的指令信息。

Currently I'm achieving this by doing the following: 目前,我正在通过以下操作实现这一目标:

<div *ngIf="foo; else noFoo">
  <!-- Show things -->
</div>

<div *ngIf="bar; else noBar">
  <!-- Show things -->
</div>

<ng-template #noFoo>
  <div class="message">
    <h4>No Foo</h4>
    <p>Please do foo to continue.</p>
  </div>
</ng-template>

<ng-template #noBar>
  <div class="message">
    <h4>No Bar</h4>
    <p>Please do bar to continue.</p>
  </div>
</ng-template>

While this is working fine, it results in quite a few templates with very similar code. 尽管这很好用,但它导致了很多模板的代码非常相似。 Instead I would like to do something like: 相反,我想做类似的事情:

<div *ngIf="foo; else showMessage">
  <!-- Show things -->
</div>

<div *ngIf="bar; else showMessage">
  <!-- Show things -->
</div>

<ng-template #showMessage>
  <div class="message">
    <h4>{{ heading }}</h4> <!-- get dynamic heading -->
    <p>{{ message }}</p> <!-- get dynamic message -->
  </div>
<ng-template>

A nudge in the right direction would be greatly appreciated. 朝正确方向轻推将不胜感激。 Thanks! 谢谢!

Solution

I was able to use the answer provided to create the following: 我能够使用提供的答案来创建以下内容:

Template: 模板:

<ng-container *ngIf="!foo; showFoo">
  <ng-container *ngTemplateOutlet="showMessage; context: messages.noFoo"></ng-container>
</ng-container>

<ng-template #showMessage let-heading="heading" let-message="message">
  <div class="message">
    <h4>{{ heading }}</h4>
    <p>{{ message }}</p>
  </div>
</ng-template>

Component: 零件:

public messages: any = {
  noFoo: { heading: 'No Foo', message: 'Please do foo to continue.' },
  noBar: { heading: 'No Bar', message: 'Please do bar to continue.' }
}

Use ngTemplateOutletContext. 使用ngTemplateOutletContext。 This lets you pass a parameter or variable into a template to be used. 这使您可以将参数或变量传递到要使用的模板中。

Documentation here => https://angular.io/api/common/NgTemplateOutlet 这里的文档=> https://angular.io/api/common/NgTemplateOutlet

I have used this to create a lot of elements that act and look similar, but needed a few things modified between them. 我使用它来创建许多行为相似的元素,但需要在它们之间进行一些修改。

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

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