繁体   English   中英

Angular 2+ Content Projection和Component属性绑定

[英]Angular 2+ Content Projection and Component property binding

我在有关Angular Content Projection的工作上有些固执。 我想将一个组件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属性。

你们有想法吗?

我不知道使用ng-content是否可行。 我用<ng-container>解决了(如果您的要求还可以):

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-container [ngTemplateOutlet]="template" [ngTemplateOutletContext]="{ $implicit: it }"></ng-container>
    </div>
  </div>
</div>

AppComponent

<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>

ImageComponent

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

...

@Input()
item: any;

是Stackblitz的例子证明了这一点。

希望这可以帮助。

暂无
暂无

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

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