Showing posts with label AngularJS2 JavaScript. Show all posts
Showing posts with label AngularJS2 JavaScript. Show all posts
AngularJS2 architecture

AngularJS2 architecture

AngularJS2 architecture

The Angular 2 application application consists of the following eight components:
  • 1, modules (Modules)
  • 2, components (Components)
  • 3, template (Templates)
  • 4, Metadata
  • 5, data binding (Data Binding)
  • 6, directives (Directives)
  • 7, Services (Services)
  • 8, Dependency Injection
The following figure shows how each part works with each other:
Templates in the diagram are composed of Angular extended HTML syntax. The Components class is used to manage these templates. The application logic is done by service, then the service and components are packaged in the module, and finally through the boot Root module to start the application.
Then we will separate the above eight parts:

Module

A module consists of a piece of code that can be used to perform a simple task.
Angular applications are modular, and it has its own modular system: NgModules.
Each Angular should have at least one module (root module), which can be named: AppModule.
The Angular module is a class with a @NgModule decorator that receives a metadata object that describes the properties of the module.
Several important attributes are as follows:
  • Declarations - The view class belongs to this module. Angular has three types of view classes: components, instructions, and pipes.
  • Exports - Statement (Declaration) subset of the template components may be used in other modules.
  • Imports - modules in this module component template that need to be exported by other classes.
  • Providers - the creator of the service. The module adds them to the global service table so that they can be accessed in any part of the application.
  • Bootstrap - the main view of the application , called the root component , which is the host of all other application views. Only the root module needs to be set in the bootstrap property.
One of the simplest root modules:

App / app.module.ts file:

Import { NgModule } from ' @ angular / core ' ; import { BrowserModule } from ' @ angular / platform-browser ' ; @ NgModule ( { imports : [ BrowserModule ] , providers : [ Logger ] , declarations : [ AppComponent ] , exports : [ AppComponent ] , bootstrap : [ AppComponent ] } ) export class AppModule { }
Next, we boot the root module to start the application, the development process is usually in the main.ts file to guide AppModule, the code is as follows:

App / main.ts file:

Import { platformBrowserDynamic } from ' @ angular / platform-browser-dynamic ' ; import { AppModule } from ' ./app.module ' ; platformBrowserDynamic ( ) . BootstrapModule ( AppModule ) ;

Component (Components)

A component is a template's control class that is used to handle the views of the application and logical pages.
Components are the foundation and core of the Angular application that can be used throughout the application.
The component knows how to render itself and configure dependency injection.
The component interacts with the view through some APIs made up of attributes and methods.
There are three steps to creating an Angular component:
  • Introduce the Component decorator from @ angular / core
  • Build an ordinary class and decorate it with @Component
  • In @Component, set the selector custom label , and the template template

Templates

The default language for Angular templates is HTML.
We can use the template to define the view of the component to tell Angular how to display the component. The following is a simple example:
<Div>
Website Address: {{site}}
</ Div>
In Angular, the default use of double brackets as interpolation syntax, the middle of the braces is usually a component attribute variable name.

Metadata

Metadata tells Angular how to handle a class.
Consider the following case we have a component called Component, which is a class until we tell Angular that this is a component so far.
You can attach metadata to this class to tell Angular Component that it is a component.
In TypeScript, we decorate the decorator.

Examples

@Component ({
   Selector: 'mylist',
   Template: '<h2> rookie tutorial </ h2>'
   Directives: [ComponentDetails]
})
Export class ListComponent {...}
The @Component decorator accepts a configuration object and marks the class that follows it as a component class.
Angular builds and displays components and their views based on this information.
Configuration item in @Component Description:
  • Selector - a css selector that tells Angular to find a <mylist> tag in the parent HTML and then create the component and insert it in the tag.
  • TemplateUrl - The address of the component HTML template.
  • Directives - an array containing the components or instructions that the template needs to depend on.
  • Providers - An array that contains the dependency injection required by the service on which the component depends.

Data binding

Data binding provides a simple and consistent way for applications to display data and data interactions, which is a mechanism for managing the values ​​inside an application.
Through this mechanism, you can from the HTML inside the value and assignment, making the data read and write, data persistence operation becomes more simple and quick.
As shown in the figure, there are four forms of data binding syntax. Each form has a direction - from the DOM, to the DOM, two-way, as indicated by the arrow in the figure.
  • Interpolation : Displays component values ​​in HTML tags.
    <H3>
    {{Title}}
    <Img src = "{{ImageUrl}}">
    </ H3>
    
  • Attribute Binding : Sets the attribute of the element to the value of the attribute in the component.
    <Img [src] = "userImageUrl">
    
  • Event Binding : Fires when the component method name is clicked.
    <Button (click) = "onSave ()"> Save </ button>
    
  • Bidirectional Binding : Use the NgModel directive in Angular to make it easier to bidirectionally.
    <Input [value] = "currentUser.firstName"
           (Input) = "currentUser.firstName = $ event.target.value">
    

Directives (Directives)

Angular templates are dynamic. When Angular renders them, it modifies the DOM according to the instructions.
The instruction is a class with "instruction metadata". In the TypeScript, the metadata is attached to the class via the @Directive decorator.
Include the following three types of instructions in Angular:
  • Attribute directive: an instruction that is used as an attribute of an element.
  • Structure directive: used to change the structure of the DOM tree
  • Component: As an important subclass of the instruction, the component can be seen essentially as an instruction with a template.
<Li * ngFor = "let site of sites"> </ li>
<Site-detail * ngIf = "selectedSite"> </ site-detail>
* NgFor tells Angular to generate a <li> tag for each item in the sites list.
* NgIf means that the SiteDetail component is included only if the selected item exists.

Services (Services)

The service in Angular2 is a standalone module that encapsulates a specific function and can be used by others for injection.
Services are divided into a variety of categories, including: values, functions, and the required characteristics of the application.
For example, when duplicate code is present in multiple components, code is multiplexed by extracting duplicate code into the service.
Here are a few common services:
  • Log service
  • data service
  • Message bus
  • Tax Calculator
  • Application configuration
The following example is a log service that logs the log to the browser's console:
Export class Logger {
  Log (msg: any) {console.log (msg);}
  Error (msg: any) {console.error (msg);}
  Warn (msg: any) {console.warn (msg);}
}

Dependent injection

Inversion of Control (IoC) is a design principle in object-oriented programming that can be used to reduce the coupling between computer codes. One of the most common ways is called Dependency Injection (DI), there is a way called "Dependency Lookup" (Dependency Lookup).
By controlling the reversal, the object is created by an external entity that controls all the objects within the system, passing it a reference to the object it relies on. It can also be said that dependencies are injected into the object.
In the traditional development model, the caller is responsible for managing the dependency of all objects. The dependency is always a nightmare, and in the dependency injection mode, this management is passed to the Injector, which is responsible for the object when the software is running Replace, not at compile time. This control is reversed, the characteristics of running injection is dependent on the essence of the implant.
Angular can see what components the component needs by looking at the parameter type of the constructor. For example, the constructor of the SiteListComponent component requires a SiteService:
Constructor (private service: HeroService) {}
When Angular creates a component, it first looks for an Injector for the services it needs.
The injector is a container that maintains a service instance that holds the previously created instance.
If there is no requested service instance in the container, the injector creates a service instance and adds it to the container, and then returns the service to Angular.
When all the services are resolved and returned, Angular will call these components as arguments to the constructor of the component. This is dependent on the injection.
AngularJS2 JavaScript environment configuration

AngularJS2 JavaScript environment configuration

AngularJS2 JavaScript environment configuration

In this section we will show you how to configure the AngularJS2 execution environment.
This section uses JavaScript to create Angular applications, and of course you can also use TypeScript and Dart to create Angular applications.
The file directory structure used in this section is as follows:

Create a configuration file

Create a directory

$ Mkdir angular-quickstart
$ Cd angular-quickstart

Load the required libraries

Here we recommend using npm as a package management tool, if you have not installed npm or do not understand npm can view our tutorial: NPM use introduction .
Create the package.json file with the following code:

Package.json file:

{ " Name " : " angular2-QuickStart " , " Version " : " 1.0.0 " , " scripts " : { " Start " : " NPM Lite RUN " , " Lite " : " Lite-Server " } , " License " : " ISC " , "Dependencies " : { " @ Angular / Common " : " 2.0.0 " , " @ Angular / Compiler " : " 2.0.0 " , " @ Angular / Core " : " 2.0.0 " , " @ Angular / Forms " : " 2.0.0 " , " @ angular / http " : " 2.0.0 " , "@ Angular / platform-browser " : " 2.0.0 " , " @ angular / platform-browser-dynamic " : " 2.0.0 " , " @ angular / router " : " 3.0.0 " , " @ angular / upgrade " : " 2.0.0 " , " core-js " : " ^ 2.4.1 " , " reflect-metadata " :" ^ 0.1.3 " , " rxjs " : " 5.0.0-beta.12 " , " zone.js " : " ^ 0.6.23 " , " angular2-in-memory-web-api " : " 0.0.20 " , " Bootstrap " : " ^ 3.3.6 " } , " devDependencies " : { "Concurrently " : " ^ 2.0.0 " , " lite-server " : " ^ 2.2.0 " } }
As npm official website mirror domestic visit is too slow, here I use the Taobao npm mirror, the installation method is as follows:
$ Npm install -g cnpm --registry = https: //registry.npm.taobao.org
After the implementation we can use the cnpm command to install the module:
$ Enpm install
After the success of the implementation, the angular-quickstart directory will generate a node_modules directory, which contains the examples we need this module.

Create the Angular component

Component is the foundation and core of the Angular application, a component that wraps a specific function, and the components work together to assemble into a complete application.
In general, a component is a JavaScript class for controlling view templates.
Next we create an app directory in the angular-quickstart:
$ Mkdir app
$ Cd app
And add the component file app.component.js, as follows:

App.component.js file:

( Function ( App ) { App . AppComponent = ng . Core . The Component ( { Selector : ' My-App ' , Template : ' <h1 of> <h1 of /> My first application Angular ' } ) . Class ( { constructor : Function ( ) { } } ) ; } ) ( window . App || ( window .App = { } ) ) ;
Next we have to analyze the following code:
We created a visual component named AppComponent by chaining the Component and Class methods in the global Angular core namespace ng.core.
The Component method takes a configuration object with two properties. The Class method is where we implement the component itself. In the Class method, we add properties and methods to the component, which bind to the corresponding view and behavior.

Module

Angular applications are modular, ES5 does not have a built-in modular system, you can use third-party module system, and then we create a separate namespace app for the application, the file code can be wrapped in IIFE (immediate execution function expression):
(Function (app) {
}) (Window.app || (window.app = {}));
We pass the global app namespace object into IIFE and initialize it with an empty object if it does not exist.
Most of the application files output the code by adding something to the app namespace, and we output the AppComponent in the app.component.js file.
App.AppComponent =

Class defines the object

The AppComponent class in this example has only one empty constructor:
.Class ({
 Constructor: function () {}
});
When we want to create a practical application, we can use attributes and application logic to extend the object.

Component Defines the object

Ng.core.Component () tells Angular that the class definition object is an Angular component. The configuration object passed to ng.core.Component () has two fields: selector and template.
ng . Core . the Component ( { Selector : ' My-App ' , Template : ' <h1 of /> <h1 of> My first application Angular ' } )
Selector for a host HTML element defines a simple CSS selector my-app. When Angular encounters a my-app element in the host HTML it creates and displays an AppComponent instance.
The template attribute holds the formed template.

Add NgModule

The Angular application consists of the Angular module, which contains the components required by the Angular application and anything else.
Next we create the app / app.module.js file as follows:

App.module.js file:

( Function ( App ) { App . The AppModule = ng . Core . NgModule ( { Imports : [ ng . PlatformBrowser . BrowserModule ] , Declarations : [ App . AppComponent ] , on Bootstrap : [ App . AppComponent ] } ) . Class ( { constructor :Function ( ) { } } ) ; } ) ( window . App || ( window . App = { } ) ) ;

Start the application

Add app / main.js file:

App / main.js file:

( Function ( app ) { document . AddEventListener ( ' DOMContentLoaded ' , function ( ) { ng . PlatformBrowserDynamic . PlatformBrowserDynamic ( ) . BootstrapModule ( app . AppModule ) ; } ) ; } ) ( window . App || ( window . App = { } ) ) ;
We need two things to start the application:
  • Angular platformBrowserDynamic (). BootstrapModule function.
  • The above mentioned application root module AppModule.
Next, create index.html as follows:

Index.html file:

< Html > < head > < meta charset = " utf-8 " > < title > Angular 2 instance - rookie tutorial (runoob.com) </ title > < meta name = " viewport " content = " width = device-width, Initial-scale = 1 " > < link rel = " stylesheet " href = " styles.css " > <! - 1.Load script -> <! - IE need polyfill -> < script src = " node_modules / core-js / client / shim.min.js " > </ script > < script src = " node_modules / zone.js /dist/zone.js " > </ script > < script src = " node_modules / reflect-metadata / Reflect.js " > </ script > < script src = " node_modules / rxjs / bundles / Rx.Js " > </ script > < script src = " node_modules/@angular/core/bundles/core.umd.js " > </ script > < script src = " node_modules/@angular/common/bundles/common.umd. Js " > </ script > < script src = " node_modules/@angular/compiler/bundles/compiler.umd.js " > </ script > <Script src = " node_modules/@angular/platform-browser/bundles/platform-browser.umd.js " > </ script > < script src = " node_modules / @ angular / platform-browser-dynamic / bundles / platform-browser- Dynamic.umd.js " > </ script > <! - 2. load 'modules' -> < script src = ' app / app . Component . Js ' > </ Script > < Script the src = ' App / App . Module1 . JS ' > </ Script > < Script the src = ' App / main . JS ' > </ Script > </ head > <-! 3. display application - -> < body > < my-app > Loading ... </ my-app > </ Body > </ html >
Index.html analysis
  • 1, load the JavaScript library we need;
  • 2, load our own JavaScript files, note the order;
  • 3. We added the <my-app> tag to the <body> tag.
The execution is: When Angular calls the bootstrapModule function in main.js, it reads the AppModule's metadata, finds AppComponent in the boot component, finds the my-app selector, locates an element named my-app, and then And then load the contents of this label.

Add some style

Styles.css file code:

Styles.css file:

H1 { color: # 369 ; Font-family: Arial , Helvetica , sans-serif ; Font-size: 250 % ; } Body { margin: 2 em ; }
Open the terminal and enter the following command:
$ Npm start
Visit http: // localhost: 3000 /, the browser displays the result:

Popular Posts