My question is quite simple.
In the router-outlet
I display my pages for example /contact
, /home
or /meetus
(How) can I display the name of the active component in the {{title}}
?
Is this even possible or do I have to move my title bar inside every component?
You can create a an AppService which holds the application title
and provides it as an observable (with accessor method such as get
and set
).
@Injectable()
export class AppService {
private title = new BehaviorSubject<String>('App title');
private title$ = this.title.asObservable();
constructor() {}
setTitle(title: String) {
this.title.next(title);
}
getTitle(): Observable<String> {
return this.title$;
}
}
Then in a component (let's say the AppComponent) which will hold (and show) the title
, you subscribe to the appService#getTitle()
method and update the title
property accordingly.
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title: String;
constructor(private appService: AppService) { }
ngOnInit() {
this.appService.getTitle().subscribe(appTitle => this.title = appTitle);
}
}
Now in every component you inject the AppService
(when needed to update the title) and call the appService#setTitle()
. For example, a hello
component:
@Component({
selector: 'hello',
template: `<p><b>Hello</b> component content</p>`,
styles: []
})
export class HelloComponent {
constructor(private appService: AppService) { }
ngOnInit() {
this.appService.setTitle('Hello Component');
}
}
See this Working Demo (Tested with Angular 6)
You can use the Angular titleService to display the page title in the header component like below:
Header component .ts:
export class AppComponent {
public constructor(private titleService: Title ) { }
}
Header component .html:
<div class="title-bar">
{{titleService.getTitle()}}
</div>
Then in any component you can set the page title using the Angular titleService and it will automatically change in the title and header sections:
export class AppComponent implements OnInit { {
public constructor(private titleService: Title ) { }
ngOnInit() {
this.titleService.setTitle("Component's title");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With