Angular 2将数据父传递给子组件

时间:2017-04-04 18:37:41

标签: javascript html angularjs angular angular2-template

我有两个组件,叫做app.component和child.component。我想将数据从父传递给子。我的代码如下。我在哪里弄错了?

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 { }

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

只需更改此行就可以了

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

或者如果你想做

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

@echonax给出了答案。