How to synchronously read route data in AppComponent before first render

Discussão em 'Angular' iniciado por bambi, Setembro 11, 2025.

  1. bambi

    bambi Guest

    In our Angular application, our AppComponent template decides whether to show the full app layout (topbar, banner, ) or a standalone login screen. Roughly, the template looks like this:

    <ng-container *ngIf="user || isPublicRoute; else showLogin">
    <app-topbar></app-topbar>
    <app-banner></app-banner>
    <router-outlet></router-outlet>
    </ng-container>

    <ng-template #showLogin>
    <app-login></app-login>
    </ng-template>


    We determine isPublicRoute from the data field of the active route, which we currently do in ngOnInit like this:

    ngOnInit() {
    this.router.events.subscribe(event => {
    if (event instanceof RoutesRecognized) {
    this.isPublicRoute = event.state.root.firstChild.data.isPublicRoute;
    }
    });
    }


    When the user navigates directly to a public route such as:

    { path: 'auth/:name', component: LoginComponent, data: { isPublicRoute: true } }



    isPublicRoute is initially undefined during the very first change detection cycle, because our logic only sets it asynchronously inside the router events subscription. That means:


    • On the first paint, user is null and isPublicRoute is undefined


    • So the *ngIf condition is false


    • Angular renders the else branch (<app-login> manually) instead of letting the router render LoginComponent in the <router-outlet>

    A few milliseconds later, RoutesRecognized fires, isPublicRoute becomes true, and the layout flips to show the <router-outlet> version. This causes a double-render / flicker.

    I want to synchronously read the data.isPublicRoute of the initially matched route before the first render of AppComponent, so that the correct branch is rendered on the first change detection pass and no flicker occurs.

    In other words, is there a way to get the currently matched ActivatedRouteSnapshot (or similar) inside the AppComponent constructor or ngOnInit, without waiting for router events like RoutesRecognized or ActivationEnd?

    Continue reading...

Compartilhe esta Página