Reputation: 4310
I am trying to make a global header in Angular6, with a dynamic list of hyperlinks, which are different for each page. The hyperlinks always reference some page, relative to the current URL. But the routerLink-s do not work relatively in the global header. This means that, when I have a routerlink in the app root header and I try to make relative links to the current, lazy loaded module, which is currently in use and which I have loaded a menu for.
Meaning, if I am on an URL
http://example.com/company/8/employee
And the global menu holds a hyperlink
<a routerLink="./profile">
Then clicking on that routerLink, will take me to example.com/profile. It acts as an absolute link. Now if, on the same page, I insert the same code into the employee component, which is loaded as the main body, it works differently, in it that it will redirect me to.
http://example.com/company/8/employee/profile
I do not understand, why wouldn't it take the global router url state as the relativity base, but instead it tries to route from root, where the header is - in the router tree.
How can I possibly manage global relative menus in the header in Angular, when the relative URL-s do not work correctly there?
Upvotes: 1
Views: 2978
Reputation: 4310
I found an answer a few weeks later.
You are allowed to pass in relativeTo to the router, which helps in these cases. You can forward another components ActivatedRoute and use that as a relativity base.
this._router.navigate(['../../method'], {relativeTo: this._activatedRoute});
Upvotes: 1
Reputation: 4129
Since ./
is a prefix of the routerLink
, it will consider the current URL as the base for its redirection.
./
is nothing but a relative path, so if you put <a routerLink="./profile">
in the app.component
, it will redirect to example.com/profile
and if you put the same link in the employee.component
, it will redirect to http://example.com/company/8/employee/profile
If you need absolute path redirection, just add /
(ex: <a routerLink="/profile">
) so that irrespective of the component, it will get redirect to example.com/profile
Upvotes: 1