DevEng
DevEng

Reputation: 1194

Angular 4 - Components Not Loading After Custom Routing

I've followed the Heros tutorial from Angular's website. I have 2 components that I added with custom routing inside app-routing.module.ts However, once I set up routes, neither of my components Address or Auth load when I visit their route. The app shell app.component loads along with its HTML just fine but my components do not. I added ngOnInit to my components and they do not fire when I visit the url, so for some reason my components are not working after I added custom routing. When I visit either /address or /auth the app component fires and I see

INSIDE APP COMPONENT

in the console, however I do not see any console log from the address or auth component.

app.module

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

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { AddressComponent } from './address.component';
import { AuthComponent } from './auth.component';


@NgModule({
  declarations: [
    AppComponent,
    AddressComponent,
    AuthComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AddressComponent }      from './address.component';
import { AuthComponent }  from './auth.component';

const routes: Routes = [
  { path: '', redirectTo: '/address', pathMatch: 'full' },
  { path: 'address', component: AddressComponent },
  { path: 'auth', component: AuthComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

auth.component.ts

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

@Component({
    selector: 'app-auth',
    templateUrl: './auth.component.html'
})
export class AuthComponent implements OnInit{
  ngOnInit(): void {
    console.log("INSIDE APP COMPONENT");
  }
}

auth.component.html

<div>
    <h3>Authentication & Authorization Page </h3>
</div>

app.component.ts

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

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

export class AppComponent implements OnInit{
  ngOnInit(): void {
    console.log("INSIDE APP COMPONENT");
  }
}

Upvotes: 0

Views: 2018

Answers (1)

user9351802
user9351802

Reputation:

You must have <router-outlet></router-outlet> in app.component.html as that is where the components render.

Upvotes: 2

Related Questions