Saturday, September 23, 2017

How to create angular 4 module

This tutorial assuming all prerequisite to start an Angular 4 application has been properly setup with Angular cli.

To create angular 4 module, follow the steps below.
1. navigate to the root directory of your Angular 4 application.

2. run the following command to generate a new module class
    ng generate module moduleName

    eg. ng generate module ferrari
3. run the following command to generate a new component under the above module
    ng generate component moduleName/componentName

    eg. ng generate component ferrari/ferrari-list
4. create a routing class in the same directory with module class  

    eg. ferrari-routing.module.ts

5. enter the following content in routing class
import { NgModule }            from '@angular/core';
import { RouterModule }        from '@angular/router';
import { FerrariListComponent } from './ferrari-list/ferrari-list.component';

  imports: [RouterModule.forChild([
  { path: '', redirectTo: 'ferrariList', pathMatch: 'full'},
  { path: 'ferrariList',    component: FerrariListComponent},
  exports: [RouterModule]

export class FerrariRoutingModule {}

6. import the routing file to module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FerrariListComponent } from './ferrari-list/ferrari-list.component';
import { FerrariRoutingModule } from './ferrari-routing.module';

  imports: [
  declarations: [FerrariListComponent ]

export class FerrariModule { }

7. lazy load the module in app-routing.module.ts

    "{ path: 'ferrari', loadChildren: 'app/ferrari/ferrari.module#FerrariModule' },"

8. the newly created module is ready to use by calling the path in routerLink

    eg. <a routerLink="ferrari">Ferrari</a>


No comments:

Post a Comment


Related Posts Plugin for WordPress, Blogger...