angularanimationangular-routingangular-activatedroute

Change routes when child component activate


I want to do a login page with password reset page. In the page, only a tiny part of the page will change when i click on "reset password" so the view will be like this :

Login page:

<div class="container">
   <div *ngIf="route is login">
      <login-component></login-component>
   </div>
   <div *ngIf="route is password forget">
      <password-forget-component></password-forget-component>
   </div>
</div>

When i click on password forgot button, i want the url to change from "/login" to "/login/forgot-password" for example. But it's in the same component and i don't know how to do this...

I think that in the component.ts i have to listen to ActivatedRoute, check if the route is /login/forgot-password, and if so make the state like this.state = 'password-forgot' (and if route is /login the state would be this.state = 'login'), but it's juste an intuition.

If you have better way of doing that also it would be nice thank you

bonus : if i can make the change of views in a transition animation !


Solution

  • In this case, I would use a router-outlet and rely on Angular routing.

    LoginPageComponent - lets assume that this component contains all the common parts that won't change. It also has a router outlet for the part that does.

    <div class="container">
       <router-outlet></router-outlet>
    </div>
    
    // in routing config
    
    [
      // Other routes
      //... 
      {
        path: 'login',
        component: LoginPageComponent,
        children: [
          {
            path: '',
            component: LoginComponent
          },
          {
            path: 'forgot-password',
            component: PasswordForgetComponent
          },
        ]
      }
    ]
    

    This assumes that you don't have another router-outlet on the same level. If you do, you'll likely need to use named router outlets.

    Hope that helps :)