简体   繁体   中英

routing to and from the parent component in angular4

Senario: I have 2 component in my app. I want to load the first component on page load and the component will have a link to navigate to the second component. The second component would in turn have a link to navigate back to the first component.

I am able to route with 2 routerLink above the router-outlet and move to and fro using the link. But how can I achieve the above scenario? Any basic plunker example would help.

I believe you have achieved everything. You only need to know how to achieve the same without using routerLink link. So here is the solution,

  • Assume `homeComponent` is the component which loads when app starts.
  • It has a button to go to about page(string coming from HTML & using typescript code)
  • It has a router.navigate method which takes an appropriate route name and navigate it accordingly.
  • And Vice versa

home.html

<button (click)="goto('about')"> go to about page </button>

home.ts

import {Router} from '@angular/router'

export class HomeComponent{
    consturctor(private router:Router){}

    goto(navigateTo:string){
          this.router.navigate([navigateTo])  //this line will take you to about component
    }
}

about.html

<button (click)="goto('home')"> go to about page </button>

about.ts

import {Router} from '@angular/router'

export class AboutComponent{
    consturctor(private router:Router){}

    goto(navigateTo:string){
          this.router.navigate([navigateTo])  //this line will take you to home component
    }
}

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