2017-04-04 138 views
1

我有兩個組件稱爲app.component和child.component。我想將數據從父母傳遞給孩子。我的代碼如下。我在哪裏犯錯?Angular 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給出了答案艾爾雷給出了答案。

相關問題