【问题标题】:Correct way to render @ContentChildren QueryList changes呈现@ContentChildren QueryList 更改的正确方法
【发布时间】:2023-03-03 09:46:01
【问题描述】:

我在渲染组件时遇到问题 这是代码示例。

<my-component>
  <ng-template *ngFor="let item of data">
    <child-component>
      <div>
        {{ data.title }}
      </div>
    </child-component>
  </ng-template>
</my-component>

在 my-component.ts 中

@ContentChildren(TemplateRef) template: QueryList<TemplateRef<any>>;
ngAfterContentInit(): void {
  this.template.forEach(item => {
     const template = this.viewTemplateRef.createEmbeddedView(item);
     template.detectChanges();
  });
}

当我将某些内容推送到数据中时,我需要显示一个新的子组件。如果我尝试做这样的事情:

this.template.changes.subscribe((result) => {
    this.template.forEach(item => {
       this.viewTemplateRef.createEmbeddedView(item);
    });
});

我有无限循环。这样做的正确方法是什么?

这里是示例:https://stackblitz.com/edit/angular-8pvrhq

【问题讨论】:

  • 你能在 stackblitz.com 上提供一个演示代码吗?这个问题需要进一步澄清
  • 如果你想告诉子组件它们应该被刷新,你可以在将新项目推送到数据数组后添加this.changeDetectorRef.detecChanges()。是否需要 ng-template?
  • @ShashankVivek stackblitz.com/edit/…
  • @KamilAugustyniak 请看我的例子stackblitz.com/edit/angular-8pvrhq
  • 为什么要在那里使用ViewContainerRef

标签: angular typescript rxjs angular8


【解决方案1】:

所以这是不可能的,我不能使用 ng-template 来传递数据。 感谢大家的支持!

<my-component>
  <child-component *ngFor="let item of data">
    <div>
      {{ data.title }}
    </div>
  </child-component>
</my-component>

为我解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2023-03-28
    • 1970-01-01
    • 2013-01-21
    • 2012-01-01
    相关资源
    最近更新 更多