Home > Blockchain >  How to add Angular routing for three distict views
How to add Angular routing for three distict views

Time:02-22

We are migrating an AngularJS 1.8 application to Angular 13 and I'm unable to find any hints on how to create three distinct views using Angular routing. The views are:

  • main
  • monitoring
  • onboarding

Each view has a distinctive layout where information is shown within a single router-outlet. The app-component.html just contains <router-outlet></router-outlet> and I want to place each view inside this outlet.

I have the following routes defined:

const routes = [
  { path: '',
    pathMatch: 'full',
    component: MainComponent,
    children: [
      { path: 'mainsub', component: MainSubComponent }
    ]
  },
  { path: 'onboarding',
    pathMatch: 'full',
    component: OnboardingComponent,
    children: [
      { path: 'onboardingsub', component: OnboardingSubComponent }
    ]
  },
  { path: 'monitor',
    pathMatch: 'full',
    component: MonitorComponent,
    children: [
      { path: 'monitorsub', component: MonitorSubComponent }
    ]
  }
];

In the MainComponent I want to navigate to the first child:

constructor(private router:Router, private route:activatedRoute) {};

ngOnInit() {
  this.router.navigate(['mainsub'], {relativeTo:this.route});
}

However, this fails as the route mainsub is unknown.

What am I missing here?

CodePudding user response:

Try with firstChild:

constructor(route: ActivatedRoute) {
  route.url.subscribe(() => {
    console.log(route.snapshot.firstChild.data);
   });
}

CodePudding user response:

Apparently I missed a lot ;)

Upon more searching online I found this article about the uses of pathMatch. In short I needed to use the following routes (for the main view):

const routes = [
{
  path: '', pathMatch: 'prefix', component: MainComponent,
  children: [
    { path: '', pathMatch: 'full', redirectTo: 'mainsub' },
    { path: 'mainsub', component: MainSubComponent }
  ]
};

This also removes the need to add the router redirect in the MainComponent.

CodePudding user response:

If you want monitoring and onboarding components to be the children of the main component (appears from your question) you may have to do it this way:

const appRoutes: Routes = [
  { path: '', redirectTo: 'main', pathMatch: 'full'},
  { path: 'main', component: MainComponent, children: [
      {path:'monitoring', component: MonitoringComponent, outlet: 'c'},
      {path:'onboard', component: OnBoardComponent, outlet: 'c'},
    ] },
];

then your router outlet looks like this:

<router-outlet name="c"></router-outlet>

And finally the links should be:

<a [routerLink]="['/main', { outlets: { c: ['monitoring'] } }]">
   Monitoring
</a>

<a [routerLink]="['/main', { outlets: { c: ['onboard'] } }]">
   Onboard
</a>

let me know if it works.

  • Related