27

Angular is it possible to detect if query Paramter has changed? I have a Component that handles 2 query paramters and according to what paramter you come with it sets some variables true or false. The Problem is if im on my component with queryparameter 1 the qp can change to the second paramter without leaving the component and in that case i need to set variables diffrently. So how do I detect that? Is that even possible?

3
  • Is that even a required use case, I dont understand when do someone actually need a query param in angular. why cant u pass input to coponent Commented Dec 28, 2017 at 7:42
  • @JinsPeter direct link for instance ? Commented Dec 28, 2017 at 7:47
  • @JinsPeter If, for instance, your have some param to pass through your entire application (i.e. your url looks like mydomain.com/#myParam/myRoute), and for some reason you refuses to use global variables. Commented Jul 31, 2018 at 13:36

3 Answers 3

45

You can subscribe to the params in the root component

constructor(route:ActivatedRoute) {
    route.queryParams.subscribe(p => console.log(p.myQueryParam)); // you can also do this in ngOnInit
}

See also https://angular.io/api/router/ActivatedRoute

You can have query params on other route levels as well, but then they are called matrix parameters.

See also the end of this section https://angular.io/guide/router#route-parameters-required-or-optional

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to hear. The 2nd part was only additional information in case you didn't know about the difference between query and matrix parameters.
4

You can subscribe to the params observable provided by ActivatedRoute module to observe changes in the query parameters.

constructor(private route:ActivatedRoute) {
    this.route.params.subscribe(
        (params:Params)=>{
            console.log(params['yourId']);
    };
)}

2 Comments

params is for route params, not for query params.
@GünterZöchbauer your comment made me to understand
1

In my case i wanted to reload page if queryParams changed to new...

Router was:

tabs/home/product?id=1984

So I wanted to call productDetails() again if id params is changed!

Solution

constructor(){
 //Recive Product Id 
  activatedRoute.queryParamMap.subscribe((data) => {
    if (this.product_id != undefined && this.product_id != 
        data['params'].id) {
        console.log('we can reload page');
        this.product_id = data['params'].id
        this. productDetails()
   }else{
    this.product_id = data['params'].id
    }
   })
}

it Worked For me! Hope it will Help :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.