typescript - 在特定路由隱藏標頭 - angular 6
我想隱藏標題,只在一個路由中。
假設我有三條路線,route1、route2 和 route3。
而我有一個名為 app-header 的元件。
我希望當使用者進入 route1 時,元件 app-header 被隱藏,並在其他兩個路由中顯示此元件。
我在 Stack Overflow 上找到了一些主題,但沒有一個對我有幫助 =/
你們可以給我一些幫助嗎?
這是我的程式碼:
app.component.ts
export class AppComponent implements OnInit { showHeader = true; constructor( private router: Router ) { this.router.events.subscribe(event => this.modifyHeader(event)); } ngOnInit() { } modifyHeader(location) { // This method is called many times console.log(location.url); // This prints a loot of routes on console if (location.url === '/route1') { this.showHeader = false; } else { this.showHeader = true; } } }app.component.html
<app-header *ngIf="showHeader"></app-header> <router-outlet></router-outlet>
我正在使用 Angular 6.1.4
答案#1
既然你知道想要檢測哪條路由,並且似乎在應用元件中已有解決方案的想法,我建議可以過濾路由器事件,如下所示:
export class AppComponent implements OnInit {
showHeader = true;
constructor(
private router: Router
) {
this.router.events.pipe(
filter(e => e instanceOf NavigationEnd)
).subscribe(event => this.modifyHeader(event));
}
ngOnInit() {
}
modifyHeader(location) { // This method is called many times
console.log(location.url); // This prints a loot of routes on console
if (location.url === '/route1') {
this.showHeader = false;
} else {
this.showHeader = true;
}
}
}
答案#2
在路由器出口新增功能
<router-outlet (activate)="modifyHeader()"></router-outlet>
在你的建構函式中
router;
constructor(private _router: Router ) {
this.router = _router;
}
你的 modifyHeader 函數
modifyHeader() { // This method is called many times
console.log(this.router.ur); // This prints a loot of routes on console
if (this.router.ur === '/route1') {
this.showHeader = false;
} else {
this.showHeader = true;
}
}
如果你遇到任何問題,請告訴我。
