7

所以我试图在我的组件中的特定位置显示子组件。

我有以下内容:

@Component({
  selector: 'app-item-list',
  template: `
<p *ngFor="let item of items">
  {{item.order}}
  <!-- display content of child component here -->
</p>`
})
export class ItemListComponent implements OnInit, AfterContentInit {

  //Get all child components of the type ItemComponent and store them.
  @ContentChildren(ItemComponent, {descendants: true}) 
  items?: QueryList<ItemComponent>;
  constructor() { }

  ngOnInit() {
  }
    
  ngAfterContentInit(): void {
      
  }

}

@Component({
  selector: 'app-item',
  template: `
<p>
  item works!
</p>
<ng-content></ng-content>
`
})
export class ItemComponent implements OnInit {

  @Input() order?: string;
  constructor() { }

  ngOnInit() {
  }

}

我尝试使用它来显示它,<ng-content select="item">但这没有用。

具有以下内容:

<app-item-list>
  <app-item order="2">
    test2
  </app-item>
  <app-item order="1">
    test1
  </app-item>
</app-item-list>

预期的输出是

2
item works!
test2
1
item works!
test1

https://stackblitz.com/edit/angular-ivy-2aibgt

4

4 回答 4

6

我可以向您推荐一个在 Angular 材质库中使用的解决方案。

  • 将组件的内容包装app-item<ng-template>标签中

item.component.html

<ng-template>  <----------------------------- wrapper
  <p>
    item works!
  </p>
  <ng-content></ng-content>
</ng-template>
  • 然后我们可以获取一个参考TemplateRef

item.component.ts

@ViewChild(TemplateRef, {static: true}) template: TemplateRef<any>;
  • app-item-list最后我们可以在组件循环中使用它

item-list.component.html

<p *ngFor="let item of items">
  {{item.order}}
  <ng-template [ngTemplateOutlet]="item.template"></ng-template>
</p>

分叉的 Stackblitz

于 2020-07-20T10:21:24.653 回答
0

确实没有办法使用ng-content(据我所知)来实现这一点。 ng-content仅用于静态内容投影。

看看这里的用例 - https://github.com/angular/angular/issues/8563 - 第 2 段证实了您必须使用带有 viewref 的查询来执行您想做的事情,即解决方案@yurzui 提供。

您始终可以使用选择器静态选择要投影的内容的哪一部分,但我怀疑这不是您要查找的内容:

<ng-content select="[order=2]">
</ng-content>
<ng-content select="[order=1]">
</ng-content>
于 2020-07-23T07:19:12.300 回答
0

您可能错过了selectitem-list.component.html

item.component.html

<p>item works</p>
<ng-content select="[body]">
</ng-content>

item-list.component.html

<p *ngFor="let item of items">
  <app-item >
  <div body>
      {{item.order}}
  </div>
  </app-item>
  test2
</p>

参考:Stackblitz 示例

于 2020-07-24T13:54:13.727 回答
-1

看看这个。早些时候,我认为没有办法实现你的输出,但我终于想通了。

我所做的是消除该@ContentChildren方法,而是用组件items Input传递的方法替换它app。我遍历项目,显示订单和相应的app-item组件。

于 2020-07-20T08:21:57.453 回答