Search code examples
angularangular-routing

Automatic redirection from child component to parent component


I currently have a problem with angular routing.

When I try to access the child path of a component loaded with lazy load, the path appears in the address bar for a very small instant and immediately after, it redirects to the parent component's path.

Example, if I want to access localhost:4200/dummy/table, it redirects to localhost:4200/dummy, if I try to navigate through a [routerLink].

If I directly enter localhost:4200/dummy/table in the address bar, it loads the module correctly and displays the child component.

Cleaning up the code a bit to simplify the example my menu would look something like this

<ul>
  <li *ngFor="let item of menu" [routerLink]="item.url"> 
      {{ item.title }} 
      <ul>
        <li *ngFor="let subItem of item.children" [routerLink]="[item.url, subItem.url]">
            {{ subItem.title }}
        </li>
      </ul>
  </li>
</ul>

And the rest of the code if you do not mind I put it as images

app-routing: enter image description here

dummy-module: enter image description here

menu.json: enter image description here

Does anyone know what could be happening to me?

According to the {enableTracing: true} it enters the route but exits it


Solution

  • It is because of the nested elements, the parent and the child both have the routerLink attribute set. I suggest wrapping the parent in a span or an anchor tag to remove the nesting of the routerLinks. An example is provided below.

    <ul>
      <li *ngFor="let item of menu"> 
          <span [routerLink]="item.url"> {{ item.title }} </span>
          <ul>
            <li *ngFor="let subItem of item.children" [routerLink]="[item.url, subItem.url]">
                {{ subItem.title }}
            </li>
          </ul>
      </li>
    </ul>```