Skip to content

Instantly share code, notes, and snippets.

@agneym
Created March 27, 2020 10:00
Show Gist options
  • Save agneym/7fa3cdd8dec37cf6d10fdfd8a93bef57 to your computer and use it in GitHub Desktop.
Save agneym/7fa3cdd8dec37cf6d10fdfd8a93bef57 to your computer and use it in GitHub Desktop.
// Set a page title in app.module.ts
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
RouterModule.forRoot([
// ProductListComponent does not have a title
{ path: '', component: ProductListComponent },
// This page has a title
{ path: 'new', component: NewRouteComponent, data: { title: 'New Page' } },
])
],
providers: [
Title,
],
declarations: [
AppComponent,
TopBarComponent,
ProductListComponent,
NewRouteComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
// In App.component.ts
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { NavigationEnd } from '@angular/router';
// Store this in constant file or something
const PAGE_TITLE = 'INDEX.HTML';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(
private activatedRoute : ActivatedRoute,
private router: Router,
private titleService: Title
) {
}
ngOnInit() {
this.setTitle();
}
setTitle() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
const { title = PAGE_TITLE } = this.activatedRoute.firstChild.snapshot.data;
this.titleService.setTitle(title);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment