fangio
fangio

Reputation: 1786

Route navigation in Angular4 not reacting

I have made an Angular4 component and the page that it generates has a button to navigate to another page. I don't get any errors and the pageUrl changes but the content of the page stays the same.

Here is my code:

app.component.ts

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

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})

export class AppComponent {

constructor(private router: Router){}

username = "";
password = "";
log = function () {
   if (this.username != "" && this.password != "") {
     console.log(this.username + "   " + this.password);
     this.router.navigate(['/dashboard']);
   }
}
}

app.module.ts

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

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';


@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
  ],
  imports: [
     BrowserModule,
     FormsModule,
     RouterModule.forRoot([
   {
    path: 'dashboard',
    component: DashboardComponent
   }
 ]
 )
 ],
 providers: [],
 bootstrap: [AppComponent],
 })
 export class AppModule {
 }

app.component.html

<div class="outer-container">
  <div class="inner-container">
   <div class="centered-content">
     <div class="center"><img src="../favicon.png"></div>
      <label class="addText"> Username: </label><input [(ngModel)] 
        ="username" class="addText"><br>
      <label class="addText"> Password: </label><input [(ngModel)] 
        ="password" type="password" class="addText"><br>
      <div class="center"><button (click) ="log()">Log in</button></div>
     </div>
  </div>
</div>

Upvotes: 1

Views: 72

Answers (2)

AVJT82
AVJT82

Reputation: 73377

To achieve what you want, have the app.component only to include the router-outlet:

@Component({
  selector: 'app-root',
  template: `
        <!-- Views go here-->
        <router-outlet></router-outlet>     
  `,
})
export class AppComponent { }

And then have a separate component for each view you want. So in your case you'd want to create a LoginComponent, which would then route to the DashboardComponent from there.

PS Of course this is expandable and you could add a header component tag in the AppComponent html, or whatever else and so on and so on. But just to showcase this simple use case.

Upvotes: 1

Raed Khalaf
Raed Khalaf

Reputation: 2065

you need to specify where to display the DashboardComponent
add this tag to tell angular the location where to display the component results from router

<router-outlet></router-outlet>

Upvotes: 0

Related Questions