Hide elements based on routing in Angular2 rc1

2019-02-02 07:21发布

I have some elements I want on every page except the login page. I'd like to use ngIf or possibly the hidden property of the elements to hide those elements when the user is on the login page.

I have tried this:

<div [hidden]="router.isRouteActive(router.generate('/login'))">

based on this question and answer: In Angular 2 how do you determine the active route?

And have also tried this:

 <div *ngIf="!router.isRouteActive(router.generate('/login'))">

but haven't had any success.

For reference here is the component that matches this html.

import { Component, OnInit } from 'node_modules/@angular/core';
import { HTTP_PROVIDERS, XHRBackend } from 'node_modules/@angular/http';
import { Routes, Router, ROUTER_DIRECTIVES } from 'node_modules/@angular/router';

import { LoginService } from './login/login.service';
import { LoginComponent } from './login/login.component';
import { UserComponent } from './user/user.component';

@Component({
    selector: 'portal',
    templateUrl: 'portal/portal.component.html',
    directives: [ROUTER_DIRECTIVES, LoginComponent, UserComponent ],
    providers: [
        HTTP_PROVIDERS,
        LoginService
    ]
})

@Routes([
    { path: '/login', component: LoginComponent},
    { path: '/user/:username', component: UserComponent}
])

export class PortalComponent implements OnInit{
    private router: Router
    constructor() {}

    ngOnInit() {
        this.router.navigate(['/login']); 
    } 
}

The documentation for isRouteActive is pretty slim, the same for generate. Any direction on a better way to achieve this behavior?

11条回答
Luminary・发光体
2楼-- · 2019-02-02 07:33

I had to do something similar in my code. I did this programmatically by creating the list of routes I wanted to exclude my element from showing in.

In my class, I injected the Location object from @angular/common.

public isHidden() {
  let list = ["/login"],
      route = this.location.path();

  return (list.indexOf(route) > -1);
}

Then in my template, I use the hidden attribute and bind it to my function.

<div id="elementToHide" [hidden]="isHidden()"></div>

查看更多
疯言疯语
3楼-- · 2019-02-02 07:34

RxJS example (Observable):

@Component({
  ...
})
export class AppComponent{
    hideElement$: Observable<boolean> = this.router.events
        .pipe(
            filter((event) => event instanceof NavigationEnd),
            map((data: any) => data.url === '/login')
        );
}
<ng-container *ngIf="!(hideElement$ | async)">
  <p>Hide me on Login page!</p>
</ng-container>
查看更多
我想做一个坏孩纸
4楼-- · 2019-02-02 07:34

Based off of @Michelangelo's Comment:

In Your Component:

import { Routes, Router } from 'node_modules/@angular/router';

export class YourComponent implements OnInit{
     constructor(public router: Router ) {
    }
}

In HTML:

<ng-container *ngIf="!router.url.includes('admin')">
    <p>The content you want to hide when in the above url path</p>
</ng-container>
查看更多
劫难
5楼-- · 2019-02-02 07:36

I would try router.generate(['/login']) rather than router.generate('/login').

This syntax sometimes is tricky.

I hope this helps in your case

查看更多
霸刀☆藐视天下
6楼-- · 2019-02-02 07:42

You can hide/show elements by checking the url for specific component,

Modify your component.ts file like this,

import { RouterModule, Router, NavigationEnd } from '@angular/router';

hideElement = false;

constructor(private router: Router) {
  this.router.events.subscribe((event) => {
    if (event instanceof NavigationEnd) {
      if (event.url === '/login') {
        this.hideElement = true;
      }  else {
        this.hideElement = false;
      }
    }
  });
}

Use this hideElement property in component.html

<div [hidden]="hideElement">
查看更多
孤傲高冷的网名
7楼-- · 2019-02-02 07:53

This is what I did for Angular2 RC5 router :

import {Router} from '@angular/router';

public location = '' ;

constructor(private  _router : Router) 
{      
  this.location = _router.url;
}

In HTML :

<div *ngIf = "location == '/home' ">
</div>

Hope this helps !

查看更多
登录 后发表回答