我试图在某些路线匹配时隐藏某个组件,我已经使用了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);
// }
}
由于
答案 0 :(得分:1)
使用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;
}