Javascript 角度2将数据从父组件传递到子组件

Javascript 角度2将数据从父组件传递到子组件,javascript,html,angularjs,angular,angular2-template,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.

我有两个组件,分别是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!';
}
    import { AppComponent } from './app.component';
    import { Component, Input } from '@angular/core';

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

}
child.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!';
}
    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>
<div>{{input}}</div>
如果将[input]=父对象到子对象写入模板,则表示引用的是不存在的父对象组件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>
来源:

如果将[input]=父对象到子对象写入模板,则表示您引用的是不存在的父对象组件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>

来源:

只要改变这一行,你就可以开始了

<child input="parent to child"> </child>
或者如果你想做的话

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

@echonax已经给出了答案。

只要换一行就可以了

<child input="parent to child"> </child>
或者如果你想做的话

<child [input]="parent to child"> </child>
@echonax已经给出了答案