9 routing angular angular-router
我想根据 Angular 中的当前 url 更改某个标题。所以 component.ts 看起来像这样:
import {Router} from '@angular/router';
//code
public name: string
constructor(
public router: Router
) {}
getName()
{
if(this.router.url === "/some_list")
{this.name = "List"}
else if(this.router.url === "/detail")
{this.name = "Detail"}
}
Run Code Online (Sandbox Code Playgroud)
进而
<a>{{this.name}}</a>
Run Code Online (Sandbox Code Playgroud)
现有的答案,例如如何检测 Angular 中的路线变化?无法告诉我在路由更改后如何做某事(更改 = true 或 false)。那么如何在 url 更改时运行此函数,以便标题根据当前视图?
你可以subscribe到router event中app.component.ts。每次更改route.
constructor(location: Location, router: Router) {
// decide what to do when this event is triggered.
router.events.subscribe(val => {
if (location.path() != "/something") {
// do something
} else {
// do something else
}
});
}
Run Code Online (Sandbox Code Playgroud)
如果它多次调用,请尝试此操作
router.events.filter(event => event instanceof NavigationEnd).subscribe(val => { // here your code... })
Run Code Online (Sandbox Code Playgroud)
注意:我没有试过这个
在路由器的每个导航启动事件中,您都可以获得 url 和 fire 功能。在你 app.component.ts
ngOnInit(){
this.router.events.subscribe(event =>{
if (event instanceof NavigationStart){
console.log(event.url)
this.routerChangeMethod(event.url);
}
})
}
routerChangeMethod(url){
this.title = url;
}
Run Code Online (Sandbox Code Playgroud)
你的 app.component.html 是..
{{title}}
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12887 次 |
| 最近记录: |