如何在Angular2中的主组件和详细信息组件之间进行相互通信?

won*_*rld 28 angular

angular2网站上有一个主要细节示例.我不能按照下面的例子中的模式.

在我的例子中,我有三个组件(1)customershome(2)客户和(3)customerdetails.该customershome组成的客户(主),并为CustomerDetails(详细信息).在客户组件中,我可以选择客户,客户的详细信息应显示在customerdetails组件中.

如何进行从客户组件到customerdetails组件的单向通信?

<div style="display: flex;">
    <div style="width:25vw">
        <customers></customers>
    </div>
    <div style="width:75vw; margin:5px">
        <customerdetails></customerdetails>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

rob*_*ald 27

这是一个使用父<customer-browser>组件 <customer-list><customer-detail>子组件的简单应用程序.

http://plnkr.co/edit/aEjlwIKKhcErWAnIhY3C?p=preview

浏览器本身只接受一组客户作为输入,并具有内部selectedCustomer属性.

列表组件接受相同的列表,并公开"selected"属性,并发出selectedChange输出事件.此语法允许双向绑定,并绑定到父级的selectedCustomer属性.

detail组件只接受一个客户输入,该输入绑定到父的selectedCustomer属性.


Kan*_*han 10

试试这个 -

@Component({
  selector: 'child',
  inputs: ['model'],
  template: `<h3>child</h3> 
    <div>{{model.prop1}}</div>
    <div>{{model.prop2}}<div>`
})
class Child {

}


@Component({
  selector: 'my-app',
  directives: [Child],
  template: `
  <h3>Parent</h3>
  <button (click)="updateModel()">update model</button>
  <child [model]="parentModel"></child>
  `
})
class App {
  parentModel = { prop1: '1st prop', prop2: '2nd prop' };
  constructor() {}
  updateModel() { this.parentModel.prop1 += ' more'; }
}
Run Code Online (Sandbox Code Playgroud)