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

标签 angular transclusion angular2-ngcontent

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

期望的最终结果应该是开发人员只需将整个标记写在一个地方(比方说在 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>

carousel.component.html:

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

carousel-item.component.html:

<ng-content></ng-content>

最佳答案

我认为唯一的解决方案是使用 @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 绑定(bind)动画触发器。我假设 @HostBingind() 被设计为仅适用于标准 html 属性(样式、类等),但似乎我实际上可以绑定(bind)任何东西(字面意思是任何东西)。

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

关于angular - 将属性传递给 ng-content 中的组件(属性在标记所在的组件中不可用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44345156/

相关文章:

mysql - 从 Angular2 组件向 node.js 发送数据

javascript - 包含 ng-template 的指令中的 Angular 嵌入(通用 Confirm Modal)

javascript - *ngFor 在 ng-content Angular 的元素上

javascript - 获取生成的隐藏字段的值

angular - 在 Angular 5 中呈现 View 之前等待数据

Angular DI 提供者与 viewProviders

typescript - 类本身可以看到嵌入的内容吗?

angularjs - 何时使用 Angular 嵌入

angular - 当父组件使用 ng-content Angular 时从子组件访问父组件

Angular 2引用@ContentChild的动态实例