簡體   English   中英

帶有參數的組件中的Angular2調用組件

[英]Angular2 calling component within component with parameter

我有一個帶有評論的詳細信息頁面。 對於單個注釋,我創建了一個@Component。 技巧是,每個評論都可以包含子評論。

這是我的details.html的樣子:

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

而且single-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示例中的“詳細信息”頁面是home.html,該頁面也包含@Component本身。

這是Angular2錯誤還是根本無法實現這種行為? 我的解決方案是顯示嵌套的注釋,但是由於無法加載第二條注釋,因此我有點陷入困境。

是否有解決方案,或者是實現我想做的更好的方法?

謝謝大家的幫助。

更新

隨着@NgModule的引入以及將directives遷移到@NgModule forwardRef不再是必須的了。

原版的

如果要在內部使用一個組件(遞歸),則需要像其他任何組件或指令一樣將其添加到providers ,因為@Component()裝飾器位於類之前,並且在聲明該類之前不能對其進行引用,需要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完成:

柱塞示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM