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)
小智 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)
| 归档时间: |
|
| 查看次数: |
13766 次 |
| 最近记录: |