I have looked quite some time into output from angular, but everywhere I only find a way to emit events. In my case, I have a parent with a router inside, and I wish to change the title based on a value from the child. So when I load route 1 I was thinking to emit a string via ngOnInit, but this doesn't work. I get the feeling that the way I want to accomplish this is not how it's supposed to be done. Any advice? The data is static and won't change in the child. Should I do an ngIf in the parent instead and check for the route?
<div> here i want the title
<router-outlet> <router-outlet>
<div>
CodePudding user response:
You can use a service to share date between components.
Create a Subject in a service and subscribe to it in the main component. Using a Subject
it's better than BehaviorSubject
because doesn't emit a initial value.
Use this observable to emit the new title from each child component.
app.service.ts
...
titleChanged$ = new Subject<string>();
constructor() {}
getTitleChanged$() {
return this.titleChanged$.asObservable();
}
setTitle(title: string) {
this.titleChanged$.next(title);
}
...
app.component.ts
...
this.appService
.getTitleChanged$()
.pipe(delay(0))
.subscribe((title) => {
this.title = title;
});
...
I've created a demo on stackblitz
CodePudding user response:
two options:
- you can listen to the route change in the parent component, and change the title according to it.
- you can store the title in a variable in some service as
behaviorSubject
and change its value from the child component, and listen to it in the parent component.