In this Scenario I am having 3 component the namely component-1,component-2,component-3. Component-2 and Component-3 are hosted in Component-1 I want to send data after clicking button in component-2 to component-3. Thanks In Advance
Asked
Active
Viewed 294 times
2
-
I have added Image for reference – Mani Teja Aug 22 '17 at 14:14
-
You can use `@Input` and `@Output` in Angular 2 for communicating between components. – Anurag Singh Bisht Aug 22 '17 at 14:15
-
Using Rxjs subject , behaviour subject is the best solution for your scenario . – Soumya Gangamwar Jan 25 '20 at 14:09
2 Answers
2
You can implement this by using the @Input and @Output decorator methods available in Angular 2/4.
Those are very simple to use. Just keep the shared data at Component 1 and do the two way binding of that data with Component 2 and 3. Make sure to trigger the change event whenever there is change in data from any of Component 2 or 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>

Ashvin777
- 1,446
- 13
- 19
1
Use a service to share data between components.
SERVICE
export class MyService {
public someVariable: string = ""
// .....
}
COMPONENT 1 (Typescript)
import { MyService } from "./myService.service"
// ......
constructor(public ms: MyService) {}
setValue(val){
this.ms.someVariable = "Hello!" // Alter the variable in the service
}
COMPONENT 2 (Typescript)
import { MyService } from "./myService.service"
// ......
constructor(public ms: MyService) {}
COMPONENT 2 (HTML)
<h1>{{ ms.someVariable }}</h1> <---- Will print Hello! in your HTML markup

Jeremy Thille
- 26,047
- 12
- 43
- 63