带有ngFor的组件接受模板并将其传递给子代,该如何做?

时间:2018-07-19 10:39:18

标签: angular templates components

我正在开发Angular 6应用。 我有一个组件 BelloComponent ,该组件呈现在 @Input项目上传递的列表。

@Component({
  selector: 'bello',
  template: `
    <ul *ngIf="items?.length">
      <li *ngFor="let item of items">
        ???
      </li>
    </ul>
`
})
export class BelloComponent {
  @Input() items: Array<Object>;
}

使用者 AppComponent 使用 BelloComponent 。 如何将列表从AppComponent呈现到BelloComponent标签内的模板?

@Component({
  selector: 'my-app',
  template: `
<bello [items]="cacche_list">
  <b>{{ name }}, puzza value: {{ puzza }}</b>
</bello>`
})
export class AppComponent  {

  cacche_list = [
    { name: 'cacca 1', puzza: 3 },
    { name: 'cacca 2', puzza: 5 },
    { name: 'cacca 3', puzza: 66 },
    { name: 'cacca 4', puzza: 5 },
    { name: 'cacca 5', puzza: 2 },
    { name: 'cacca 6', puzza: 12 },
  ];
}

堆叠闪电战是这样的:https://stackblitz.com/edit/angular-exbhsv?file=src%2Fapp%2Fapp.component.ts

我认为我缺少什么,如何告诉 BelloComponent 如何在 ngFor 中呈现元素?如何访问从 AppComponent 呈现的单个项目?

2 个答案:

答案 0 :(得分:0)

唯一缺少的是您的{{item.name}}中的ngFor

<ul *ngIf="items?.length">
  <li *ngFor="let item of items">
    {{item.name}}
  </li>
</ul>

Demo

答案 1 :(得分:0)

您只需在贝娄组件中使用<ng-content></ng-content>



@Component({
  selector: "bello",
  template: `
    <ul *ngIf="items?.length">
      <li *ngFor="let item of items">
        <ng-content></ng-content>
      </li>
    </ul>
  `
})
export class BelloComponent {
  @Input() items: Array<Object>;
}