Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - *ngIf route is a certain param

Tags:

angular

I have a route /main/item:id

which looks something like:

http://localhost:5000/main/item/-JJHkhfghsiu45ve

In my html I want to be able to use an *ngIf to show something if this is the route or not. I do not want to use router outlet for this.

The issue I am having might be regarding the param.

I am doing something like:

 <div *ngIf="this.router.url !== '/main/item:id'">

But this does not work for me as it sees this as always false. Thanks

like image 745
Pete Avatar asked Aug 02 '26 13:08

Pete


1 Answers

What I would do is set your *ngIf equal to a boolean value. then use ngOninIt or something along those lines to change the value of that bool depending on your Url. Here is a working plunker. NOTE: only focus on the home.ts file in the plunker. you can also prove that this is working by changing the *ngIf value as necessary.

P.S sorry the plunker is filled with irrelevant info here is the important stuff though...

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

@Component({
    template: `<h1>home</h1> <button (click)="Nav()">nav to second</button>
     <div *ngIf="!mybool">I am only showing if my route is home!</div>
   `,
  styleUrls:['style.css'],
})

export class HomeComponent {
 mybool:boolean;
 constructor(private router: Router,){
 console.log(this.router.url);
 }

ngOnInit(
  showDiv(){
  if(this.router.url === '/'){
    this.mybool=false;
  }
}
)
like image 128
Bean0341 Avatar answered Aug 05 '26 12:08

Bean0341



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!