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

时间:2017-06-03 14:50:04

标签: angular transclusion angular2-ngcontent

我正在尝试开发旋转木马。

期望的最终结果应该是开发人员只需将整个标记写在一个地方(让我们说app.component.html中只有一个options属性)然后,轮播将会接管。

问题是来自carousel.component我需要在carousel-item.component上设置一些属性(app.component应该与...无关的属性...但所有标记都在{{1} }})。

我怎样才能做到这一点?

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>

carousel.component.html:

<div class="carousel-stage"> <ng-content></ng-content> </div>

carousel-item.component.html:

1 个答案:

答案 0 :(得分:1)

我认为唯一的解决方案是使用@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);
    }
  }
}

然后,在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;
  }
}

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

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