angularangular-routerangular-auxiliary-routes

How to return from auxiliary routes in an Angular 12 app


I have an Angular 12 app which displays a list of things on the left and the detail of the selected thing on the right. Because users should be able to get a deeplink to a specific thing, the selection is done through the Angular router. This part can be easily done and there are plenty of examples to achieve this.

The app also has a modal to, e.g., create a new thing, and for this modal the app uses auxilary routes so that external sites can directly link to it.

Screenshot

At first, I was confused by the URLs generated, e.g. when I have the modal open, I get

gb/en_GB/(layout/1//modal:new)

, but selecting items with an open modal works fine and it seems to be the way that the Angular router constructs the URL from the URL tree.

What doesn't work is closing the modal once it was opened. I'm trying to achieve this currently by setting the modal outlet to null but it doesn't work:

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent {
  showCloseButton = false;

  constructor(private router: Router, private route: ActivatedRoute) {}

  activate(active: boolean) {
    this.showCloseButton = active;
  }

  close() {
    this.router.navigate([{ outlets: { modal: null } }], {
      replaceUrl: true
    });
  }
}

I also have a Stackblitz with the complete example.

Questions

  1. How can I close the modal?
  2. Is it possible to have a "clean" URL afterwards (without parentheses), i.e. gb/en_GB/layout/1

Solution

  • After some trial and error, I found that I have to specify an anchor to the navigation using relativeTo. In this case, it's

    close() {
      this.router.navigate([{ outlets: { modal: null } }], {
        replaceUrl: true,
        relativeTo: this.route.parent
      });
    }
    

    which will apply a delta modal: null to the route relative to the parent of the current route (the one with RootComponent).