how to navigate one route to another in angular 2

13.4k views Asked by At

I make a two different component of angular 2 .I am learning routing from this link https://angular.io/docs/ts/latest/tutorial/toh-pt5.html

I make two component .In first component I have one button I want to move to move to second component

here is my code https://plnkr.co/edit/GBOI9avZaPGaxaLQbtak

I define routes like that

    const routes =[
      {
        path: 'ft',
        component: First
      },
      {
        path: 'sd',
        component: Second
      }
    ]

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App,First ,Second]
}) 

I am using <router-outlet>

but I am not able to move one component to another

2

There are 2 answers

0
Milad On BEST ANSWER

There you go :

@Component({
  selector: 'first',
  template: `
    <div>
      <button (click)="moveToSecond()">move to secon comp</button>
    </div>
  `,
})
export class First {
  name:string;
  constructor(private router:Router) {
  }

  moveToSecond(){
    this.router.navigate(['/sd']);
  }
}

https://plnkr.co/edit/wIuaffLskQd8GJuqLlY6?p=preview

You had heaps of errors :D

Anyway , in order to navigate to another route , you'd need to use router

0
Nate May On

You can also navigate of the button itself without calling a component function

<button routerLink="/sd">move to secon comp</button>