将属性传递给 ng-content 内的组件(标记所在的组件中不可用的属性)

MrC*_*oft 5 transclusion angular2-ngcontent angular

我正在尝试开发一个轮播。

期望的最终结果应该是开发人员只需将整个标记写入一个位置(假设在app.component.html),仅使用一个options属性,然后轮播将接管。

问题是,carousel.component我需要设置一些属性carousel-item.component(属性app.component应该与...无关,但所有标记都在app.component.html)。

我怎样才能实现这个目标?

app.component.html:

<carousel [options]="myOptions">
    <carousel-item *ngFor="let item of items">
        <img [src]="item.image" alt="" />
    </carousel-item>
</carousel>

<hr />

<carousel [options]="myOptions2">
    <carousel-item *ngFor="let item of items">
        <img [src]="item.image" alt="" />
    </carousel-item>
</carousel>
Run Code Online (Sandbox Code Playgroud)

carousel.component.html:

<div class="carousel-stage">
    <ng-content></ng-content>
</div>
Run Code Online (Sandbox Code Playgroud)

carousel-item.component.html:

<ng-content></ng-content>
Run Code Online (Sandbox Code Playgroud)

MrC*_*oft 4

我认为唯一的解决方案是与@ContentChildren()

在我的carousel.component.ts

import { ContentChildren, ... } from '@angular/core';

// ...

export class CarouselComponent implements AfterContentInit {
  @ContentChildren(ItemComponent) carouselItems;

  ngAfterContentInit() {
    this.carouselItems.forEach((item: ItemComponent, currentIndex) => {
      // Do stuff with each item
      // Even call item's methods:
      item.setWidth(someComputedWidth);
      item.setClass(someClass);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,在carousel-item.component.ts

export class ItemComponent implements OnInit, OnDestroy {
  @HostBinding('style.width') itemWidth;
  @HostBinding('class') itemClass;
  @HostBinding('@fade') fadeAnimationState;


  setWidth(width) {
    this.itemWidth = width + 'px';
  }
  setClass(class) {
    this.itemClass = class;
  }
  setAnimationState(state) {
    this.fadeAnimationState = state;
  }
}
Run Code Online (Sandbox Code Playgroud)

显然,我什至可以使用@HostBinding绑定动画触发器。我假设 @HostBingind() 被设计为仅适用于标准 html 属性(样式、类等),但似乎我实际上可以绑定任何东西(字面意义上的任何东西)。

有人有更好的解决方案吗?在我接受自己的答案之前......