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)
- ng new testapp
Say yes to include routing module.
Chose styling as required.
Create Test component
- ng new c test
Update component as follows
- import { Component, OnInit } from '@angular/core';
- import { Router } from '@angular/router';
- @Component({
- selector: 'app-test',
- templateUrl: './test.component.html',
- styleUrls: ['./test.component.scss']
- })
- export class TestComponent implements OnInit {
- public route: string;
- constructor(private rte:Router) { }
- ngOnInit() {
- this.route = this.rte.url
- }
- }
Update Test component view as follows
- Current Route {{route}}
Setup sample routing component by editing app-routing.module.ts
- import { NgModule } from '@angular/core';
- import { Routes, RouterModule } from '@angular/router';
- import { TestComponent } from './test/test.component';
- const routes: Routes = [{
- path: 'test',
- component: TestComponent
- }];
- @NgModule({
- imports: [RouterModule.forRoot(routes)],
- exports: [RouterModule]
- })
- export class AppRoutingModule { }
Implement route in app.component.html
Serve the application
- ng serve
On the landing page click the Test Route
Output
- Test Route
- Current Route /test
Articoli simili
- Is there a way to get a Bixby voice assistant on my Galaxy S7 Edge with Android 10 S9+ port ROM?
- Are there any current cell phones not made in China?
- Is there any way in c to change the value of a global variable through a function without passing it to the function?
- Is there a way to transfer a playlist from my iPhone onto iTunes on my computer?