如何在Angular2中的组件之间共享数据

时间:2017-08-22 14:13:33

标签: javascript angular typescript angular2-services angular2-directives

enter image description here

在这个场景中,我有3个组件,即组件-1,组件-2,组件-3。 Component-2和Component-3托管在Component-1中 我想在组件-2到组件-3中单击按钮后发送数据。 在此先感谢

2 个答案:

答案 0 :(得分:1)

您可以使用Angular 2/4中提供的@Input和@Output装饰器方法来实现此目的。

这些非常简单易用。只需将共享数据保留在组件1中,然后将该数据与组件2和3进行双向绑定。确保在组件2或3中的任何一个数据发生更改时触发更改事件。

//for example component 1
@Component({ ... })

export class Component1{
  private data: Data = "some data";
}

//component 2 and 3
@Component({ ... })

export class Component2{

  @Input() data: Data = "some data";
  @Output() dataChange: EventEmitter ...
  
  ngOnChanges(){
    this.dataChange.emit(this.data);
  }
}
<component1>
<component2 [(data)]="data"></component2>
<component3 [(data)]="data"></component3>
</component1>

答案 1 :(得分:0)

使用服务在组件之间共享数据。

SERVICE

 export class MyService {
     public someVariable: string = ""
     // .....
 }

组件1(打字稿)

 import { MyService } from "./myService.service"
 // ......
 constructor(public ms: MyService) {}

 setValue(val){
     this.ms.someVariable = "Hello!" // Alter the variable in the service
 }

COMPONENT 2(打字稿)

 import { MyService } from "./myService.service"
 // ......
 constructor(public ms: MyService) {}

组件2(HTML)

 <h1>{{ ms.someVar }}</h1>  <---- Will print Hello! in your HTML markup
相关问题