Kallam
Kallam

Reputation: 169

Angular 4 routing not working

I have checked the stack over flow answers on this, but none of them seem to be relevant, I have created two components page1 and page2. and declared a route in the module.ts

     import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Route, RouterModule} from '@angular/router'


import { AppComponent } from './app.component';
import { Page1Component } from './page1/page1.component';
import { Page2Component } from './page2/page2.component';


@NgModule({
  declarations: [
    AppComponent,
    Page1Component,
    Page2Component
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot([
      {path:'page1', component:Page1Component},
      {path:'page2', component:Page2Component}
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And my page1 html is as below

<p>
  page1 works!

<button (click)= 'OnbtnClick()'>Route to Page2</button>
</p>

The Component ts is as below

import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router';

@Component({
  selector: 'app-page1',
  templateUrl: './page1.component.html',
  styleUrls: ['./page1.component.css']
})
export class Page1Component implements OnInit {

  constructor(private _router:Router) { }

  ngOnInit() {
  }

OnbtnClick()
{
let abc =this._router.navigate(['/page2'])

}
}

But on clicking the button, The Url is changing, But the view remains the same, The appcomponent.html is as follows.

<div style="text-align:center">
  <h1>
    Welcome to SuperHero!
  </h1>
</div>

<app-page1></app-page1>   

Please help !!

Upvotes: 10

Views: 12670

Answers (1)

Daniel
Daniel

Reputation: 9829

AppComponent.html needs to have <router-outlet></router-outlet> directive:

<div style="text-align:center">
  <h1>
    Welcome to SuperHero!
  </h1>
</div>

<-- The view is injected here -->
<router-outlet></router-outlet>

Upvotes: 21

Related Questions