javascript - 显示我使用 @ContentChildren 或 @ViewChild 获取的组件的内容

标签 javascript angular typescript angular10

所以我试图在我的组件中的特定位置显示子组件。
我有以下内容:

@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

最佳答案

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

  • 包装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 的循环中使用它组件

  • 项目列表.component.html
    <p *ngFor="let item of items">
      {{item.order}}
      <ng-template [ngTemplateOutlet]="item.template"></ng-template>
    </p>
    
    Forked Stackblitz

    关于javascript - 显示我使用 @ContentChildren 或 @ViewChild 获取的组件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62939824/

    相关文章:

    javascript - react 形式 : dynamically add and delete to a type string array in Angular 4

    javascript - 使用 'this.currentTime' 获取视频的时间并将其重置为 'hover out' 上的起点

    java - 如何设置<s :param> value of <s:url> tag dynamically using javascript in struts2

    javascript - JavaScript 是按引用传递还是按值传递语言?

    angular - 动态添加外部背景图像 Angular 2 sanitizer

    angular - 类型 'subscribe' 上不存在属性 'OperatorFunction<unknown, any>'

    javascript - 在 React 应用程序中,哪里是启动数据加载的初始 API 服务调用的最佳位置?

    angular - 使用 Angular 从服务器动态获取翻译

    typescript - 如何在 TypeScript 中获取枚举变量的数值?

    javascript - 在新的 typescript 文件 (0.9) 中使用现有的 AMD js 模块