Wednesday, 21 February 2018

Get Url parameter using Angular

AngularQuery ParameterRouter

In this article we will be discussing about getting query parameter in Angular. In angular js 1.x, it was straight forward by using $location.search();. Now let us check how it is in Angular 2(+).

Sample Url


http://localhost:4200/experiment?userName="Prashobh"&profession="blogger"

Let us check the component code for accessing the query parameter.


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

@Component({
    selector: 'experiment-com',
    templateUrl: '../experiment/experiment.html'
})

export class experimentComponent {
    constructor(private ActiveRoute: ActivatedRoute) { }
    ngOnInit() {
        this.ActiveRoute.queryParams.subscribe((params: Params) => {
            let _queryParem = params;
            console.log(_queryParem);

        })
    }
}

Here we have used ActivatedRoute and Params to get the data and getting those info in angular ngOnInit. It is pretty straight forward.

Example result

If you want to access particular value then you can try below code.


let _queryParem = params['userName'];
console.log(_queryParem);


Now let us check another scenario.

In this case we have added data in router in the above format. Let us check how we can access this in our component.


{ path: 'form', component: FormComponent ,data :{data :'Test Data'} },


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

@Component({
    selector: 'form',
    template: '<div>Form</div>'
})

export class FormComponent {
    sub: any;
    constructor(private route: ActivatedRoute) { }
    ngOnInit() {
        this.sub = this.route
            .data
            .subscribe(value => console.log(value));
    }
}

There are other ways also there to share and access data through routes, check this link for 3 simple ways to share data through angular route. and also Share data between Angular components - 7 methods

Angular 2+Angular 4/5Query ParameterRouter

Related Info

1. Http calls in Angular with simple examples.

2. 5 different ways for conditionally adding class - Angular.

3. Angular 2/4 routing with simple examples.

4. Reusable flashy message using Angular 4

No comments :

Post a Comment