【问题标题】:Angular 2+ Content Projection and Component property bindingAngular 2+ 内容投影和组件属性绑定
【发布时间】:2019-03-23 09:47:46
【问题描述】:

我被关于 Angular 内容投影的难题所困扰。 我想将一个组件 A 投影到另一个 B 中,并在组件 A 上绑定一些属性。

例如, 我有一个 SwitchButton 组件(有多种选择)。我希望这个组件显示文本或图像。

为此,这是我的 SwitchButtonComponent (HTML):

<div class="container border rounded bg-white">
   <div class="row text-center">
      <div *ngFor="let it of items" class="col" style="cursor:pointer;">
         {{it}}
      </div>
   </div>
</div>

我省略了 ts 类,这里不需要,但它当然有一个 items 属性。 我在另一个组件中使用这个组件,如下所示:

<div>
   <switch-button [items]="['A','B','C']"></switch-button>
</div>

嗯,这很简单。它工作正常。

现在,我在项目中有一个更复杂的对象,我想显示一个图像。 它会给出:

<div>
   <switch-button [items]="[{path:'./img1.png'},{path:'./img2.png'}]">
       <img-component></img-component>
   </switch-button>
</div>

img-component 只是一个简单的组件,用于渲染图像并具有一个属性:imgPath。

在 SwitchButtonComponent 中:

<div class="container border rounded bg-white">
   <div class="row text-center">
      <div *ngFor="let it of items" class="col" style="cursor:pointer;">
         <ng-content></ng-content>
      </div>
   </div>
</div>

这里可以看到我无法绑定投影组件(img-component)的imgPath属性。

你们有什么想法吗?

【问题讨论】:

  • 我在这条线上看到了一个额外的{&lt;switch-button [items]="[{path:'./img1.png'},{{path:'./img2.png'}]"&gt;。这是故意的吗?
  • 啊!根本不是,这只是我的一个错误!我现在纠正它。谢谢:)

标签: angular components projection angular2-ngcontent


【解决方案1】:

我不知道这是否可以使用ng-content。我使用&lt;ng-container&gt; 解决了它(如果这符合您的要求):

开关按钮组件

<div class="container border rounded bg-white">
  <div class="row text-center">
    <div *ngFor="let it of items" class="col" style="cursor:pointer;">
     <ng-container [ngTemplateOutlet]="template" [ngTemplateOutletContext]="{ $implicit: it }"></ng-container>
    </div>
  </div>
</div>

应用组件

<div>
  <switch-button [items]="[{path:'./img1.png'},{path:'./img2.png'}]">
    <ng-template let-item>
      <img-component [item]="item"></img-component>
    </ng-template>
  </switch-button>
</div>

图像组件

<div>{{ item.path }}</div>

...

@Input()
item: any;

Here 是 Stackblitz 示例,展示了这一点。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 2016-07-21
    • 1970-01-01
    • 2018-01-30
    • 2023-03-23
    相关资源
    最近更新 更多