Home > Net >  In angular i want to show/hide certain elements depending on routerlinks?
In angular i want to show/hide certain elements depending on routerlinks?

Time:10-02

I have 6 URL's.

case 1 : For 3 URL's visible div name "box-A" and hide "box-B"

case 2 : For other 3 URL's visible div name "box-B" and hide "box-A"

How to write conditions according to the routerLinks. I'm using angular version 8. Thank you!

CodePudding user response:

constructor(private router: Router){
console.log(router.url);

router.events.filter(event => event instanceof NavigationEnd)
      .subscribe(event => 
       {
          this.currentRoute = event.url;         
       });
}

You can do *ngIf on the basis of the this.currentRoute property in your HTML. If you don't wanted to remove div completely from your DOM, you can also use [hidden] instead of *ngIf.

CodePudding user response:

// in your component.ts :

public canShowBoxA = false;
public canShowBoxB = false;
constructor(private router: Route) {
    this.router.events.subscribe( (val: any) => {
      this.activateDiv(this.router.url);
    });
  }

activateDiv(url: string) {
 // check url value to update canShowBoxA and canShowBoxB 
}

// in your component.html

<div *ngIf="canShowBoxB">             
 Box B
</div>

<div *ngIf="canShowBoxA">             
Box A
</div>
  • Related