1

I have some component. In this component I can get url parameter, like this:

const campaignIdParam: number = +this.route.snapshot.paramMap.get('campaignId');

Tell me how I can programmatically replace this campaignId in the address bar of the browser without reloading the page?

Update: My url like this:

http://localhost:4200/#/company/2

0

1 Answer 1

2

You can use:

this.location.replaceState(
           path, query, state
        );

From Angular docs:

/**
 * Changes the browsers URL to the normalized version of the given URL, and replaces
 * the top item on the platform's history stack.
 */
replaceState(path: string, query?: string, state?: any): void;

UPDATE:

More specifically you can use this code:

this.location.replaceState(
            this.router.createUrlTree(
                [tempUri],
                {queryParams: queryParamsObj}
            ).toString()
        );

Part of constructor for this code

constructor(private location: Location,
            private router: Router) {
}
Sign up to request clarification or add additional context in comments.

5 Comments

I saw it. But I can't understand, how to replace the campaignId, for example with this url: localhost:4200/#/company/2. For example, 2 I want to replace with 3: localhost:4200/#/company/3
queryParams just add parameter via ?, but I have url like this: localhost:4200/#/company/2
I update my answer - you can use this.router.createUrlTree for this, and update tempUri with : /company/3. You doens't use queryParams - this is parameter after ?
It is unclear how to get tempUri, the witch component can be plugged into different other components, and the URLs there will be different, not just the company. I just wanted to replace the parameter by its name
@All_Safe in your case tempUri is /company/3 or /company/2 - it is a new URI, what you need in your browser url bar.

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.