Created
March 27, 2020 10:00
-
-
Save agneym/7fa3cdd8dec37cf6d10fdfd8a93bef57 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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