如何在Angular 2中将对象从一个组件传递到另一个组件?

Ano*_*yan 55 angular2-directives angular

我有Angular组件,第一个组件使用第二个组件作为指令.它们应该共享相同的模型对象,该对象在第一个组件中初始化.如何将该模型传递给第二个组件?

Mar*_*cok 59

对于从父级到子级的单向数据绑定,请使用@Input装饰器(根据样式指南的建议)在子组件上指定输入属性

@Input() model: any;   // instead of any, specify your type
Run Code Online (Sandbox Code Playgroud)

并在父模板中使用模板属性绑定

<child [model]="parentModel"></child>
Run Code Online (Sandbox Code Playgroud)

由于传递对象(JavaScript引用类型),因此对父组件或子组件中的对象属性所做的任何更改都将反映在另一个组件中,因为两个组件都引用了同一对象.我在Plunker中展示了这一点.

如果重新分配父组件中的对象

this.model = someNewModel;
Run Code Online (Sandbox Code Playgroud)

Angular会将新对象引用传播到子组件(作为更改检测的一部分自动传播).

您不应该做的唯一事情是重新分配子组件中的对象.如果这样做,父级仍将引用原始对象.(如果确实需要双向数据绑定,请参阅/sf/answers/2423157131/).

@Component({
  selector: 'child',
  template: `<h3>child</h3> 
    <div>{{model.prop1}}</div>
    <button (click)="updateModel()">update model</button>`
})
class Child {
  @Input() model: any;   // instead of any, specify your type
  updateModel() {
    this.model.prop1 += ' child';
  }
}

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

Plunker - Angular RC.2

  • 你在做上帝的工作!对兄弟组件有什么建议吗?就我而言,我在根级别引导了 2 个。HeaderComponent 有一个搜索输入,我想与正文中的组件共享.. (2认同)

Cha*_*ani 20

组件2,指令组件可以定义输入属性(@inputTypescript中的注释).组件1可以将该属性从模板传递给指令组件.

请参阅此SO答案如何在Angular2中的主组件和详细信息组件之间进行相互通信?

以及如何将输入传递给子组件.在你的情况下它是指令.


小智 15

您还可以将数据存储在带有setter的服务中,并通过getter获取

import { Injectable } from '@angular/core';

@Injectable()
export class StorageService {

    public scope: Array<any> | boolean = false;

    constructor() {
    }

    public getScope(): Array<any> | boolean {
        return this.scope;
    }

    public setScope(scope: any): void {
        this.scope = scope;
    }
}
Run Code Online (Sandbox Code Playgroud)