带有参数的组件内的 Angular2 调用组件

Angular2 calling component within component with parameter

我有一个带有评论的详细信息页面。对于单个评论,我创建了一个@Component。诀窍是,每个评论都可以有子评论。

这是我的 details.html 的样子:

some info here...
<single-comment ngFor... [comment]="'hi comment'"></single-comment>

而单comment.html看起来像:

<ion-item no-padding>
  <small dark>
    <strong>{{comment}}</strong>
  </small>
  <ng-content></ng-content>
  <single-comment [comment]="'ANOTHER comment'"></single-comment>
</ion-item>

组件本身:

@Component({
  selector: 'single-comment',
  templateUrl: 'single-comment.html'
})
export class SingleComment {
  @Input() comment: string;

  constructor() {
  }

  ngAfterContentInit() {
        console.log('new comment', this.comment);
  }
}

事实是,第二名。子组件永远不会被调用。

我还创建了一个 Plunkr 代码,它更好地展示了示例。 Plunkr 在此处可见:https://plnkr.co/edit/w5kWE6QdbEoXIpqLI4dc?p=preview。 plunkr 示例中的 "details" 页面是 home.html,它也包含 @Component 本身。

这是 Angular2 的错误还是根本不可能出现这种行为?我的解决方案是显示嵌套评论,但由于我无法加载第二条评论,我有点陷入死胡同。

是否有解决此问题的方法或更好的方法来实现我正在尝试做的事情?

谢谢大家的帮助。

更新

随着 @NgModule 的引入以及 directives@NgModule 的迁移,forwardRef 应该不再需要了。

原创

如果你想在自身内部使用一个组件(递归),你需要像任何其他组件或指令一样将它添加到 providers,因为 @Component() 装饰器出现在 [=36= 之前] 并且 class 在声明之前不能被引用 你还需要 forwardRef

import {Component, forwardRef, Input} from '@angular/core'

@Component({
  selector: 'single-comment',
  templateUrl: 'single-comment.html',
  directives: [forwardRef(() => SingleComment)]
})
export class SingleComment {
  @Input() comment: string;

  constructor() {
  }

  ngAfterContentInit() {
        console.log('new comment', this.comment);
  }
}

您还需要确保递归在某处结束,否则您将得到堆栈溢出。在 Plunker 中,它是使用 *ngIf:

完成的

Plunker example