
在这个场景中,我有3个组件,即组件-1,组件-2,组件-3。Component-2和component-3驻留在Component-1中,我想在单击component-2中的按钮后将数据发送到Component-3。提前感谢
发布于 2017-08-22 22:17:14
您可以使用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>
发布于 2017-08-22 22:38:51
使用服务在组件之间共享数据。
服务
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
}组件2(打字)
import { MyService } from "./myService.service"
// ......
constructor(public ms: MyService) {}组件2 (HTML)
<h1>{{ ms.someVariable }}</h1> <---- Will print Hello! in your HTML markuphttps://stackoverflow.com/questions/45820062
复制相似问题