2017-03-24 8 views
1

に宣言せず、私は、2つの成分Angular2 [2.4.10]インポート子コンポーネント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: [] 
}) 

もう1つの質問 - コンポーネントの数があり、お互いに通信したい場合。それをApp.module.tsにすべてオーバーヘッドで追加するのですか?彼らは起動してロードされます。私がここに間違っていれば私を修正してください。

答えて

0

parent.component.tsに@NgModuleデコレータが含まれていてはいけません。

あなたのapp.moduleには、「宣言」セクションが必要です。モジュールに関連付けられているすべてのコンポーネントは、宣言配列に含める必要があります。

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

コンポーネントが互いに通信する方法はいくつかあります。

  • 両親を結合入力を持つ子供の親から

    • パスデータは、子イベントをリッスン
    • 親は親が@ViewChild()
    • 親を呼び出し、子どもたちが通信
    • ローカル変数を経由して、子供と対話しますサービスを介して

    このウェブサイトでは、これらのオプションに関する詳細情報を表示しています。https://angular.io/docs/ts/latest/cookbook/component-communication.html

  • +0

    私は50のようなすべてのコンポーネントを宣言する必要があるapp.moduleが心配です。先に 'directives:[ComponentName]'と一緒に使用できます – Anoop

    関連する問題