Search code examples
javascriptangularangular2-routingrouter-outlet

Angular 6 Router navigation not rendering child component in the destination component


I have an Angular 6 application with a login component and a dashboard component. Am trying to navigate to DashboardComponent on the login button click event. DashboardComponent contains a child component called WardComponent . But while navigating the to the dashboard it render only the contents other than the child component ward.How can i render the dashboard component with child component it it after the login ?

Please see my component classes below

AppComponent

<router-outlet></router-outlet>

LoginComponent.ts

  export class LoginComponent {
  constructor(private router: Router) {}

  login() {
    this.router.navigate(["/dashboard/"]);
  }
}

DashboardComponent

import { Component } from "@angular/core";
@Component({
  selector: "dashboard",
  template: `
    haii u r in dashboard compo

    <div class="form-inline" style="padding: 40px;">
      <ward *ngFor="let ward of wards" [wardNumber]="ward"></ward>
    </div>
  `
})
export class DashboardComponent {
  constructor() {}
}

WardComponent.ts

import { Component, Input } from "@angular/core";
@Component({
  selector: "ward",
  template: `
    <div class="card bg-light mb-3" style="max-width: 18rem;">
      <div class="card-header"></div>
      <div class="card-body">
        <h2 class="card-title">{{ wardNumber + 1 }}</h2>
        <button class="btn btn-primary" (click)="checkIn()">check in</button>
        <button class="btn btn-primary" (click)="checkOut()">check Out</button>
      </div>
    </div>
  `
})
export class WardComponent {
  @Input() wardNumber: Number;
  checkedIn: boolean = false;
  constructor() {}

  checkIn() {
    console.log("checked in");
    this.checkedIn = true;
  }

  checkOut() {}
}

app.module.ts

  const indexRoutes: Route = {
  path: "",
  component: DashboardComponent
};
// for all invalid routers , it will redirect to login component
const fallbackRoutes = {
  path: "**",
  component: LoginComponent
};

const routes: Routes = [
  indexRoutes,

  {
    path: "dashboard",
    component: DashboardComponent
  },

  {
    path: "ward",
    component: WardComponent
  },

  fallbackRoutes
];

@NgModule({
  declarations: [
    AppComponent,
    WardComponent,
    LoginComponent,
    DashboardComponent
  ],
  imports: [BrowserModule, RouterModule.forRoot(routes)],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Solution

  • Its because of the content of ward component is not populated correctly .i have added the content of wards in wrong place, instead of adding the wards array in WardComponent , i have put that in AppComponent.