Home > front end >  How to route to the components with the parameters in the URL
How to route to the components with the parameters in the URL

Time:11-16

I want to route to the component by sending the parameters in the URL, where it can be accessed in the component. I am not able to route to the component with the ActivatedRoute.

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HerosComponent } from './heros/heros.component';

const routes: Routes = [{ path: 'heros/:id', component: HerosComponent }];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [],
})
export class AppRoutingModule {}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { AppRoutingModule } from './app-rounting.module';

@NgModule({
  imports:      [ BrowserModule, FormsModule, AppRoutingModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.html

<hello name="{{ name }}"></hello>
<p>Start editing to see some magic happen :)</p>
<a (click)="routeToComponent()">Click to route</a>

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular '   VERSION.major;
  constructor(private router: Router) {}

  routeToComponent() {
    alert('called');
    this.router.navigate(['/heros/23']);
  }
}

heros.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-heros',
  templateUrl: './heros.component.html',
  styleUrls: ['./heros.component.css']
})
export class HerosComponent implements OnInit {

  constructor(private route: ActivatedRoute,) { 
    this.route.params.subscribe( params => console.log(params) );
  }

  ngOnInit() {
  }

}

stakblitz link to the application

CodePudding user response:

The URL parameters must be sent as additional elements in the `navigate()` function argument.
this.router.navigate(['/heros', 23]);

Update:

I just looked at your Stackblitz, it appears to be missing the <router-outlet> tag.

app.component.html

<hello name="{{ name }}"></hello>
<p>Start editing to see some magic happen :)</p>
<a (click)="routeToComponent()">Click to route</a>

<router-outlet></router-outlet>

See here for more info on <router-outlet>.

I've updated your Stackblitz.


As for the initial proposed solution about passing the URL parameters, both variants ['/heros', 23] and ['/heros/23'] work.

  • Related