簡體   English   中英

Angular2 [2.4.10]導入子組件而不聲明為AppModule

[英]Angular2 [2.4.10] Import child component without declaring into AppModule

我有兩個組成部分

parent.component.ts

@Component({
  selector: 'my-element',
  template: `  <h4>{{title}}</h4>
               <child-element></child-element> //<-- Here I want to take data from child element
              `    
})
export class ParentComponent {
  title = 'This is parent!';
}

child.component.ts

@Component({
  selector: 'child-element',
  template: `
               <h4>{{childTitle}}</h4>
              `   
})
export class ChildComponent {    
  childTitle = 'This is Child';    
}

我嘗試在parent.component.ts中添加以下內容,但它不起作用。

@NgModule({
  imports: [ChildComponent],
  providers: []
})

另一個問題 - 如果我有多個組件並希望彼此通信。 在App.module.ts中添加所有這些都會產生開銷,不是嗎? 因為他們將被裝載起來。 如果我錯了,請糾正我。

parent.component.ts不應該有@NgModule裝飾器。

在你的app.module中,你應該有一個“聲明”部分。 與模塊關聯的所有組件都應包含在聲明數組中。

@NgModule({
    declarations: [ParentComponent, ChildComponent]
})

組件可以通過多種方式相互通信。

  • 使用輸入綁定將數據從父級傳遞給子級
  • 父母聽兒童活動
  • 父通過局部變量與子進行交互
  • Parent調用@ViewChild()
  • 家長和孩子通過服務進行交流

該網站提供了有關每個選項的更多信息: https//angular.io/docs/ts/latest/cookbook/component-communication.html

暫無
暫無

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

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