Search code examples
angulartypescriptangular2-routingangular-routing

Angular Routing Login module unexpected directive imported [ERROR]


I am having this error specifically;

Unexpected directive 'LoginComponent' imported by the module 'AppModule'. Please add a @NgModule annotation. 

does anyone know what it is for? my app-routing.module is as such;

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './components/login/login.component';

const routes: Routes = [
  {
    path: 'login',
    loadChildren: './components/login/login.component#LoginModule'
  }
];

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

and app.module is as

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    LayoutModule,
    OverlayModule,
    HttpClientModule,
    LoginComponent,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: createTranslateLoader,
        deps: [HttpClient]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})

my login.component

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

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

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

  ngOnInit() { }

  onLogin() {
    localStorage.setItem('isLoggedin', 'true');
    this.router.navigate(['/dashboard']);
  }
}

where's the grief exactly? can anyone give me a hint in the right direction? AppModule contains my LoginComponent inside the imports section as expected. Then why the above error? Could you please explain? My app is expected to load the login page upon launch, ie. localhost:4200 should basically load the login just as localhost:4200/login also should.

Not very clear to me what I did wrong logically here!


Solution

  • remove LoginComponent from imports and add it to declarations

    @NgModule({
      declarations: [
        AppComponent,
        LoginComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        BrowserAnimationsModule,
        LayoutModule,
        OverlayModule,
        HttpClientModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: createTranslateLoader,
            deps: [HttpClient]
          }
        })
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    

    imports is used for importing other modules and make their functionality available to current module. components are not imported to a module in angular, modules are. components are declared as part of a module.