简体   繁体   中英

Routing issue in angular

For starters, I have started with angular a few days back and have found this weird issue in routing. I imported the "RouterModule", added the path and component accordingly. Also, added router outlet to app.component.html file. Here are my issues:

  1. I can't go from one component or page to another via the navbar. For eg If I am on home page, I can easily go to some other page, but if I want to go to a different page and click on it's link, I automatically get redirected to the home page first.

  2. All the new pages that I open still contain the complete home page code. Although, I know that it is because of adding router-outlet just on top of home page(I wrote my home page code in app.component.html), but what is a better alternative.

Ps The questions might be too beginner level, but please bear with me.

Thanks!!

  1. Make sure you navigate like this <a routerlink="/contact">Contact Page</a> . Do NOT use href.
  2. Add another component where you add the router-outlet . Then you make your "home" page the default route. Ofcourse you can keep static components outside of the outlet (maybe navbar & footer?) and add those in component side by side with the router-outlet .
  1. Make sure you have router configuration set up properly, for example.

 const routes: Routes = [ { path: "home", component: HomeComponent, children: [ { path: "child-1", component: ChildComponent1}, { path: "child-2", component: ChildComponent2 } ] }, { path: "", redirectTo: "home", pathMatch: "full" } ];

  1. Add router-outlet in your app.component.html
  2. In your parent component, in above example home.component.html add routerLink and router-outlet to load children,

 <div> <button routerLink="child-1">Child-1</button> <button routerLink="child-2">Child-2</button> <router-outlet></router-outlet> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM