[英]hide certain components on multiple routes angular 5
我正在嘗試在某些路線匹配時隱藏組件,我已經將它與1條路線一起使用,但是如果我執行多次,則無法使用
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
template: `
<app-header *ngIf="!_router.url.includes('account', 'admin', 'app')"></app-header>
<router-outlet></router-outlet>
<app-footer *ngIf="!_router.url.includes('app', 'account', 'admin')"></app-footer>
`
})
export class RootComponent {
router: string;
constructor(
public _router: Router
) {
this.router = _router.url;
}
}
現在這是行不通的,但是如果我在includes()
只有一個單詞,它是否有效?
編輯
我試圖做到這一點...
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
template: `
<app-header *ngIf="!hasMatches('app', 'account', 'admin')"></app-header>
<router-outlet></router-outlet>
<app-footer *ngIf="!hasMatches('account', 'admin', 'app')"></app-footer>
`
})
export class RootComponent {
router: string;
constructor(
public _router: Router
) {
this.hasMatches();
this.router = _router.url;
}
private hasMatches(...values: string[]): boolean {
let matchFound = false;
for (let i = 0; i < values.length; i++) {
if (this.router.indexOf(values[i]) > -1) {
matchFound = true;
break;
}
}
return matchFound;
}
// isPage(): boolean {
// const re = /^\/(account|admin|app)$/;
// return !re.test(this.router.url);
// }
}
謝謝
使用indexOf()。 下面的hasMatches()方法可以處理任意數量的參數。
HTML
<app-header *ngIf="!hasMatches('account', 'admin', 'app')"></app-header>
<router-outlet></router-outlet>
<app-footer *ngIf="!hasMatches('app', 'account', 'admin')"></app-footer>
TS
routeUrl: string;
constructor(
public _router: Router
) {
// subscribe to the router events in order to always get the current url
this._router.events.subscribe(() => this.routeUrl = this._router.url );
}
private hasMatches(...values: string[]): boolean {
let matchFound: boolean = false;
// check for null or undefined first
if(this.routeUrl){
for (i=0; i<values.length; i++){
if(this.routeUrl.indexOf(values[i]) > -1){
matchFound = true;
break;
}
}
}
return matchFound;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.