如何使用角度(角度2或4)路线更改页面的标题?

Sha*_*kti 20 angular-ui-router angular-cli angular

每当我点击或浏览URL栏中的链接时,我想更改页面的标题.如何使用Angular路线改变它?我正在使用角度版本4和角度cli.

Shu*_*rma 17

您可以使用@angular/platefor-browser使用setTitle():

import { Title } from '@angular/platform-browser';

@Component({
  selector: 'your-component',
})

export class YourComponent implements onInit {
  constructor(private title: Title) {}

 ngOnInit() {
     this.title.setTitle('Title for this component');
 }

}
Run Code Online (Sandbox Code Playgroud)

  • 它可能与此问题无关,在所有其他页面中重定向到除“setTitle”之外的其他页面后,有没有办法将其更改回来?由于此更改将在离开该页面后保留。 (2认同)

小智 12

你必须将"title"作为数据传递给你的路线

const routes: Routes = [{
  path: 'calendar',
  component: CalendarComponent,
  children: [
    { path: '', redirectTo: 'new', pathMatch: 'full' },
    { path: 'all', component: CalendarListComponent, data: { title: 'My Calendar' } },
    { path: 'new', component: CalendarEventComponent, data: { title: 'New Calendar Entry' } },
    { path: ':id', component: CalendarEventComponent, data: { title: 'Calendar Entry' } }
  ]
}];
Run Code Online (Sandbox Code Playgroud)

然后在您的Component中执行此导入:

import { Title } from '@angular/platform-browser';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
Run Code Online (Sandbox Code Playgroud)

一旦导入,我们可以注入它们:

@Component({
  selector: 'app-root',
  templateUrl: `
    <div>
      Hello world!
    </div>
  `
})
export class AppComponent {
  constructor( private router: Router,
               private activatedRoute: ActivatedRoute,
               private titleService: Title) {}
}
Run Code Online (Sandbox Code Playgroud)

要静态更新页面标题,我们可以像这样调用setTitle:

ngOnInit() {
     this.router.events
        .filter((event) => event instanceof NavigationEnd)
        .map(() => this.activatedRoute)
        .map((route) => {
            while (route.firstChild) route = route.firstChild;
            return route;
        })
        .filter((route) => route.outlet === 'primary')
        .mergeMap((route) => route.data)
        .subscribe((event) => {
            let title = 'Default Title Here'
            if(event['title']) {
                title = event['title'];
            }
            this.titleService.setTitle(title);
        });
}
Run Code Online (Sandbox Code Playgroud)

  • -1:本例中未使用`data:{title:'...'}`,因此它不直接回答问题.好像是来自@JKing提供的链接的快速复制粘贴 (10认同)
  • 有关完整代码,请参阅以下内容:https://toddmotto.com/dynamic-page-titles-angular-2-router-events (7认同)