【问题标题】:Angular 2 pass data parent to child componentAngular 2将数据父传递给子组件
【发布时间】:2017-08-30 02:49:01
【问题描述】:

我有两个组件,分别称为 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 { }

【问题讨论】:

    标签: javascript html angularjs angular angular2-template


    【解决方案1】:

    如果您将[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 已经给出了答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-01
        • 1970-01-01
        • 2017-08-04
        • 2016-06-10
        • 2021-12-24
        • 1970-01-01
        • 2021-02-23
        • 1970-01-01
        相关资源
        最近更新 更多