4

Just a little new to Angular2 world, however it was preety simpler in angular 1 by specifying {reload: false} but not able to find a similar solution in Angular 2 where I can avoid reloading the component while changing the query param in my route.

I have html template, where I am changing the query parameter on click of a button.

I have the method updateRoute({type: 'app_dependency'}) which gets called on click of the button:

  ngOnInit() {
    console.log(`ngOnInit  - is called. `);
  }
  public updateRoute(urlObject){
    let queryParams = this.activatedRoute.snapshot.queryParams;
    let updatedQuery = clone(queryParams);
    this.activeTab = updatedQuery.type || 'app_dependency';
    forEach(urlObject, (value, key) => {
      updatedQuery[key] = value;
    });
    //this.location.search({type: 'app_dependency'})
    this.router.navigate([], {
      relativeTo: this.activatedRoute,
      queryParams: queryParams
    });
  }

But every time this function gets called, it destroys the component and calls ngOnInit().

Is it possible to just change the url query (I am not changing the route but just changing the query) without reloading my component? If yes, can anyone please help me or suggest me a better approach.

9
  • Be aware that activatedRoute.snapshot should only be used if the component never gets reused (Angular Docs), what I think you're trying to achieve. Commented Sep 25, 2018 at 9:22
  • do u suggest ot have any example where i can reuse the component @Emaro Commented Sep 25, 2018 at 10:59
  • 1
    have you tried navigate( [] , { skipLocationChange: true }): ? Commented Sep 25, 2018 at 11:12
  • yes, i tried just now... but still doesnt seems to be working Commented Sep 25, 2018 at 12:55
  • 2
    Please see the stackblitz stackblitz.com/edit/…. It just does not reload the component. My guess is you might display the component on i.e. some ngIf, the condition might be temporarily changed and it causes the component to re-render. Anyway, numerous potential reasons. Commented Sep 25, 2018 at 20:03

1 Answer 1

0

I have found a solution here:
It will prevent the component from being destroyed.

constructor(
        private router: Router
      ) {
        this.router.routeReuseStrategy.shouldReuseRoute = function () {
          return true;
        };
      }
Sign up to request clarification or add additional context in comments.

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.