Angular 2 pass data parent to child component

99封情书 提交于 2019-12-11 06:48:19

问题


I have two components its called app.component and child.component. I want to pass the data from parent to child. My code is below. Where am i making mistake?

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

回答1:


If you write [input]="parent to child" to the template then it means that you are refering to the parent components this.parent to child which doesn't exists.

You can do something like this:

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

then in the template:

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

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

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




回答2:


Just change this line and you are good to go

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

Or if you want to do

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

@echonax has alredy given the answer.



来源:https://stackoverflow.com/questions/43215085/angular-2-pass-data-parent-to-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!