2017-04-04 30 views
1

私はapp.componentとchild.componentという2つのコンポーネントを持っています。親から子へデータを渡したい。私のコードは以下の通りです。どこで私は間違っているのですか?角2パスのデータ親子コンポーネント

app.component.ts

import { ChildComponent } from './child.component'; 
import { Component } from '@angular/core'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'], 
    entryComponents:[ChildComponent] 
}) 
export class AppComponent { 
    title = 'app works!'; 
} 

child.component.ts

import { AppComponent } from './app.component'; 
    import { Component, Input } from '@angular/core'; 

    @Component({ 
     selector: 'child', 
     templateUrl: './child.component.html' 
    }) 
    export class ChildComponent { 
    @Input() input :string; 

} 

app.component.html

<h1> 
    {{title}} 
</h1> 

<child [input]="parent to child"> </child> 

child.component.html

<div>{{input}}</div> 

app.module.ts

import { ChildComponent } from './child.component'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { FormsModule } from '@angular/forms'; 
import { HttpModule } from '@angular/http'; 

import { AppComponent } from './app.component'; 

@NgModule({ 
    declarations: [ 
    AppComponent, 
    ChildComponent 
    ], 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    HttpModule 
    ], 
    providers: [], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { } 

答えて

3

あなたがテンプレートに[input]="parent to child"を記述する場合、それはあなたが存在しない親コンポーネントthis.parent to childに参照のうえされていることを意味します。

あなたはこのような何か行うことができます:テンプレートで、その後

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'], 
    entryComponents:[ChildComponent] 
}) 
export class AppComponent { 
    title = 'app works!'; 
    parentInput = 'parent to child'; 
} 

を:

<h1> 
    {{title}} 
</h1> 

<child [input]="parentInput"> </child> 

出典:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child

2

はちょうどこの行を変更して、あなたは

を行ってもいいです
<child input="parent to child"> </child> 

またはしたい場合

<child [input]="parent to child"> </child> 

@echonaxは答えを与えてくれました。

関連する問題