Thursday, October 25, 2018

Feature Module example in Angular

Feature Modules are additional modules which can be added to the root module for better modularity and maintainability of the Angular applications. As the application grows it becomes difficult to maintain all the components, services etc in a single root module, hence we organize the components into sub-modules called Feature Modules and hook them to the root module.

In this example let us see how to create a FeatureModule, import it in the root module and render the contents of the FeatureModule components in the root modules components.

Assuming that we have a basic root module and component which we saw in the previous examples, let us go ahead and create a new feature module using the following command.

ng generate module FeatureModule

This command will create a new folder feature-module with a module file feature-module.module.ts inside the folder.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [CommonModule],
  declarations: []
})
export class FeatureModule { }

Now we shall create a component for the FeatureModule using the following command.

ng generate component feature-module/FeatureComponent

This command will create another folder feature-component inside the module folder and add the component files in the new folder as follows.



Now we have to export our feature components so that they can be used in the root modules components, we can do this my modifying the feature module file as follows.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature-component/feature-component.component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [FeatureComponent],
  exports: [FeatureComponent]
})
export class FeatureModule { }

Next let us import the feature component in the root component.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FeatureModule } from './feature-module/feature-module.module';

@NgModule({
  declarations: [AppComponent],
  imports: [
    RouterModule.forRoot(appRoutes)
    FeatureModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Finally let us embed the feature component in the root component by adding the feature component’s selector tag in the root component’s template.

<div>
  Root component content<br/>
  <app-feature-component></app-feature-component>
</div>

And the output will be as follows.





Search Flipkart Products:
Flipkart.com

No comments: