Casa > I > Is There A Way To Get The Current Url Or Path From Within A Angular2 Component? I'm Currently Using Angular2 Rc6.

Is there a way to get the current URL or path from within a Angular2 component? I'm currently using Angular2 rc6.

Setup a new project using Angular CLI

(For this I used Angular 7, Angular CLI 7)

  1. ng new testapp 

Say yes to include routing module.

Chose styling as required.

Create Test component

  1. ng new c test 

Update component as follows

  1. import { Component, OnInit } from '@angular/core'; 
  2. import { Router } from '@angular/router'; 
  3. @Component({ 
  4. selector: 'app-test', 
  5. templateUrl: './test.component.html', 
  6. styleUrls: ['./test.component.scss'] 
  7. }) 
  8. export class TestComponent implements OnInit { 
  9. public route: string; 
  10. constructor(private rte:Router) { } 
  11. ngOnInit() { 
  12. this.route = this.rte.url 

Update Test component view as follows

  1.  

  2. Current Route {{route}} 
  3.  

Setup sample routing component by editing app-routing.module.ts

  1. import { NgModule } from '@angular/core'; 
  2. import { Routes, RouterModule } from '@angular/router'; 
  3. import { TestComponent } from './test/test.component'; 
  4. const routes: Routes = [{ 
  5. path: 'test', 
  6. component: TestComponent 
  7. }]; 
  8. @NgModule({ 
  9. imports: [RouterModule.forRoot(routes)], 
  10. exports: [RouterModule] 
  11. }) 
  12. export class AppRoutingModule { } 

Implement route in app.component.html

  1. Test Route 
  2.  

Serve the application

  1. ng serve 

On the landing page click the Test Route

Output

  1. Test Route 
  2. Current Route /test  

De Celine

Qual laptop é melhor, o Lenovo ThinkPad E14 ou o Lenovo IdeaPad S340? :: Qual é a comparação entre o Lenovo Ideapad S145 e o Lenovo Ideapad S340 Ultrabook?