Phil Samson
Phil Samson

Reputation: 61

Use the path a user enters in the URL in the page

I'm building an app in angular 6 and i'm looking for a functionality with which i can use whatever the user is typing in the Browser's address bar in the site,

For example:

User enters domain "myproject.example/5/cool"

then the website should give output "User 5 is soo cool!"

Is there a way to read what the user types in the URL?

Thanks in advance

Upvotes: 1

Views: 605

Answers (1)

RoadEx
RoadEx

Reputation: 541

Yes, it's possible to read the url in the address bar. There's two way to do it : with the ActivatedRoute and with Router.

ActivatedRoute

ActivatedRoute will require a app-routing.module.ts with the elements you want to display in your component:

{ path: ':customerId/:state', component: YourComponent }

And, in your component :

 constructor(private route: ActivatedRoute) {
      this.route.paramMap.subscribe(params => {
        this.customerId = params.get('customerId');
        this.state = params.get('state');
    });
  }

You'll only need to construct your output with customerId and state.

Router

If you don't want to use the routing (or you can't for whatever reason), you can also use Router to read the url. You'll juste need to parse it :

 constructor(private router: Router) {
      this.href = this.router.url;
 }

Upvotes: 1

Related Questions