I have 3 components
- app.component.html
- footer.component.html
- home.component.html
content of app.component.html
<h1> Header> </h1>
<router-outlet></router-outlet>
content of footer.component.html
<footer >
<section>
</section>
</footer>
content of home.component.html
<h1>Home</h1>
<app-footer></app-footer>
<router-outlet></router-outlet>
In home.component.ts file
ngOnInit(): void {
this.http.get(this.baseUrl 'api/content').subscribe(result => {
this.Title=result.title;
this.logo=result.logo;
...
...
});
}
Fetching these data on page load in home.component.ts
file i want to pass some of the variables to footer component and app component. How can i pass these variables (Multiple) to other component.
CodePudding user response:
You can pass data between components that have a parent-child relationship by using @Input
decorator.
- Go into
footer.component.ts
and add
@Input()
data: {title: string, logo: string};
- Save the data inside
home.component.ts
into a single object:
ngOnInit(): void {
this.http.get(this.baseUrl 'api/content').subscribe(result => {
this.footerData = {title: result.title, logo: result.logo};
});
}
- Make sure you pass in the input. In
home.component.html
<app-footer [data]="footerData"></app-footer>
Alternatively you can declare multiple @Input
members in footer, one for each property.
CodePudding user response:
The 0xBobby's answer works fine with parent-child components but in more complex scenarios (with routing, for example) I would recommend using a shared service and BehaviorSubject
for communication between components. Chech this Stackblitz example based loosely on your code: https://stackblitz.com/edit/angular-jbus9x?file=src/app/app.component.ts.
First, you create a SharedService used to, well, share data between components:
@Injectable({
providedIn: 'root'
})
export class SharedService {
private sharedData$ = new BehaviorSubject<SharedData>({title: '', logo: ''});
sharedData = this.sharedData$.asObservable();
constructor() { }
setData(data: SharedData): void {
this.sharedData$.next(data);
}
The in the HomeComponent you set the data you want to share:
constructor(private sharedService: SharedService) {}
setData(): void {
this.sharedService.setData({title: this.title, logo: this.logo});
}
and finally you subscribe to the the observable in AppComponent and FooterComponent where you want to show the same data:
export class AppComponent {
data: SharedData;
constructor(private sharedService: SharedService) {}
ngOnInit(): void {
this.sharedService.sharedData.subscribe(result => this.data = result);
}
}
The advantage of this solution is that the communication works between deeply nested components, with routed componentes, with services, etc.