未加星标

Getting to Know Angular 2’s Module: @NgModule

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏
Free Course Getting Started with Angular 2

Angular 2 is the shiny new framework that comes with a lot of new concepts. Learn all the great new features.

Angular 2 has re-introduced the module concept since RC 5 onwards (and now Final Release!). Why reintroduced? It's because it exists in Angular 1!

The initial plan for Angular 2 was to drop the angular.module() and use ES6 modules instead. Throwback to the day when Igor Minar and Tobias Bosch announced the killing of ng.module() during ng-europe conference, Oct 2014.


Getting to Know Angular 2’s Module: @NgModule
Module in Angular 1

You may skip this part if you are totally new to Angular.

An Angular 1 module is a collection of:

services directives controllers filters configuration information.

You syntax will look something like this:

// ng1-my-app.js ... // Creating a new module var myModule = angular.module('myModule', []); // Defining a new module myModule .value('appName', 'MyCoolApp'); .controller('controllerName', ControllerFunction) .service('serviceName', ServiceFunction) .filter('filterName', FilterFunction); ... // Create a new module that uses myModule var anotherModule = angular.module('anotherModule', ['myModule']); Module in Angular 2

Fast forward to Angular 2. Angular Module is now called @NgModule .

Question 1Why do we need @NgModule?

Short Answer: Angular Modules help to organize an application into cohesive blocks of functionalities and extend it with capabilities from external libraries.

For longer, deeper and more technical answer, check out the explanation in the Angular blog or this document - Understanding @NgModule .

Question 2But... Don't we have javascript Modules already? We can already import and export each JavaScript file as a module, right?

Take a deep breath, long answer ahead

In Javascript Modules, every file is one module. In Angular 2, one component is normally a file (if you follow the style guide ).

Take for example, you have 10 components in your project, and that translates into 10 files. Now, given that you have another two new components - namely component A and B. These 2 components depend on the 10 components we just described above.

Prior to RC 5, this is how you do it.

// a.component.ts // import all 10 components here import { No1Component, No2Component, ... } from './components'; @Component({ selector: 'a-cmp', templateUrl: 'a-cmp.component.html', directives:[No1Component, No2Component, ...] // inject all 10 components here }) export class AComponent { }

Then, repeat the same process for component B. Now, if we were to create many more components that behave like component A and B, it surely will become cumbersome to keep including these 10 components into every other component. It is certainly not a fun thing to do! However, you can improve the code by creating barrel. Lets look at a more refactored code:

// barrel.ts // import all 10 components here import { No1Component, No2Component, ... } from './components'; // export an array of all 10 components export const groupedComponents = [No1Component, No2Component, ...];

Then change your component A code, to import the barrel to Component A

// a.component.ts import { groupedComponents } from './barrel'; @Component({ selector: 'a-cmp', templateUrl: 'a-cmp.component.html', directives:[groupedComponents] // inject all grouped components here }) export class AComponent { }

The code sure does looks neater now but you still have to include groupedComponents in every component that you need it. With @NgModule , what you need to do is this

// a.component.ts @Component({ selector: 'a-cmp', templateUrl: 'a-cmp.component.html' // no more directives, no more importing component to component }) export class AComponent { }

Yes, no more importing components / directives / pipes to each of your components (in our case, component A and B). Instead, we import all to @NgModule and all components / directives / pipes will be available throughout the components under the module .

Every Angular app has at least one module, the root module, conventionally named AppModule .

Here is how a typical AppModule will look like:

// app.module.ts @NgModule({ declarations: [ // put all your components / directives / pipes here AppComponent, // the root component No1Component, No2Component, ... // e.g. put all 10 components here AComponent, BComponent, // e.g. put component A and B here NiceDirective, AwesomePipe, ], imports: [ // put all your modules here BrowserModule, // Angular 2 out of the box modules TranslateModule, // some third party modules / libraries ], providers: [ // put all your services here AwesomeService, ], bootstrap: [ // The main components to be bootstrapped in main.ts file, normally one only AppComponent ] }) export class AppModule { }

Later on, you can bootstrap your application using this app.module.ts .

\\ main.ts ... platformBrowserDynamic().bootstrapModule(AppModule); ...

There are 3 more less commonly used @NgModule properties ( exports , schemas , entryComponents ) which I didn't include for the sake of simplicity. Check the documentation here for the full list of propertioes and its description.

How Should We Organize Modules?

There are no standard way to group modules, but the recommendations are:

Features as a module Shared utilities as a module Features as a module

Let's say your application has customer and product feature, each feature has some components / pipes / directives. Take for example:

Customer: CustomerListComponent, CustomerDetailComponent, CreateCustomerComponent, CustomerService Product: ProductListComponent, ProductDetailComponent, CreateProductComponent, ProductService

Because these features are independent from each other, you may consider to create two modules: CustomerModule and ProductModule , then import these modules to AppModule later.

Shared utilities as a module

For the functions or features that can be shared across modules and application, consider creating a shared module.

A really useful example would be for example, a translation utility in your application (e.g. Translation Service and Translation Pipe. check out my tutorial on implementing language translation in Angular 2 ). The Translation utility is actually an independent module. By creating a TranslateModule it then can be used by other modules like CustomerModule and ProductModule .

Summary

That it! If you would like to learn how to create a shared module, check out my article , as it gives you a step by step guide on creating your own TranslateModule .

If you need more in depth knowledge about @NgModule , checkout the official documentation:

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: JavaJavaScript
分页:12
转载请注明
本文标题:Getting to Know Angular 2’s Module: @NgModule
本站链接:http://www.codesec.net/view/484035.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(26)