angularangular2-routingangular-routingangular4-router

url change but still on the same page with routing angular 4?


I'm trying to do this example with angular 4 in my project. https://angular.io/tutorial/toh-pt5#add-routes

enter image description here

how to change the URL but still on the same page


Solution

  • Haha, well this is not a great question.

    Did you read the tutorial? If yes then what is the problem?

    1. You need to configure your Routes array of Route objects:

      const routes: Routes = [
        { path: 'lazysalim', component: LazySalimComponent }
      ];
      

      Path is a string representing the route in url and component is the associated Component you want to display when on this url.

    2. Add it to module (probably app.module.ts) imports via forRoot method:

      imports: [
        ...,
        RouterModule.forRoot(routes)
      ]
      
    3. You need to add <router-oultet></router-oultet> into your template. This acts as an anchor, the Component associated with the matching URL will be displayed below this anchor.

    4. You need a button or something for navigation to those paths. You can use

      <a [routerLink]="['lazysalim']">
      

      You'll be navigated to url/lazysalim` as a button. Or

         this.router.navigate(['lazysalim'])`.
      

      I hope it's not too long for you :\