Home > database >  Based on query parameter open related components in angular
Based on query parameter open related components in angular

Time:11-16

I want to know that when we open localhost:4200/signin?url=login at that time I want to open login component and when we open localhost:4200/signin?url=register at that time I have to load register component. So what is the best way to achieve this functionality.

CodePudding user response:

you can add login and register route in your app-routing.module.ts or add children in you signin route

const routes: Routes = [
    {
        path: 'signin',
        component: SigninComponent
    },
    {
        path: 'signin/register',
        component: RegisterComponent
    },
    {
        path: 'signin/login',
        component: LoginComponent
    },
];

then navigate based on the parameters by using activatedRoute

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

ngOnInit() {
    this.activatedRoute.queryParams.subscribe((params: Params) => { 
        switch (params['url']) {
           case 'login':
              this.router.navigate(['signin/login']);
              break;
           case 'register':
              this.router.navigate(['signin/register']);
              break;
}

    });
       
}

CodePudding user response:

You haven't provided full details of your code, I have no clue where your router-outlet is or what /xyz path's component is doing. But if it was me, then, I would simple add the query param logic to whatever component /xyz path maps to and check the query param inside ngOnInit()

Example:

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

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe(val => {
      const param = val['url'];
      switch (param) {
        case 'login':
          this.router.navigate(['login']);
          break;
        case 'register':
          this.router.navigate(['register']);
          break;
      }
    });
  }

Stackblitz demo

Note: if you want a solution using Promise and route guard, then add full details of your code in the qeustion.

Happy coding!

  • Related