angular 8 : Why the component is not loading?

Kishor Pawar picture Kishor Pawar · Sep 26, 2019 · Viewed 7.2k times · Source

So I created an app with angular-cli . I have following structure in src dir.

. ├── app │   ├── app-routing.module.ts │   ├── app.component.css │   ├── app.component.html │   ├── app.component.spec.ts │   ├── app.component.ts │   ├── app.module.ts │   └── notifications │   ├── notifications.component.css │   ├── notifications.component.html │   ├── notifications.component.spec.ts │   └── notifications.component.ts ├── assets ├── environments │   ├── environment.prod.ts │   └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── protocol.js ├── styles.css └── test.ts

Routes have following.

RouterModule.forRoot([
        { path: '', component: AppComponent },
        { path: 'notifications', component: NotificationsComponent}
    ])

AppComponent has Html for the login page.
Once the form is submitted I redirect to notifications component with [routerLink]="['/notifications']"

Now I am expecting <app_root></app_root> in the index.html to be populated with notifications-component.html.

First of all, is the assumption above right?

I tried to change the selector in notification-component.ts
I tried putting <app-notifications></app-notifications> in <app_root></app_root>
I tried putting <router-outlet></router-outlet> in <app_root>, app.component.html and notifications.component.html. (Only app.component.html worked. but it is showing both HTMLs.)

If the assumptions above is not right, how is it supposed to work?

P.S.

THANKS, EVERYONE FOR PROMPT RESPONSE.

I know all of your answers are right, but I could only accept one answer.

Answer

rijin picture rijin · Sep 26, 2019

A couple of changes are required to your approach:

  1. Add <router-outlet></router-outlet> to the app.component.html file.

  2. Create another component for login ( eg. LoginComponent )

  3. Update route

       RouterModule.forRoot([
        { path: '', pathMatch: 'full', component: LoginComponent },
        { path: 'notifications', component: NotificationsComponent }
       ])],
    

*Also it's not recommended to use the home path for login, you can change the url to /login and re-route if it's not authenticated.

Have a look https://stackblitz.com/edit/angular-dfhxek.