Runoob Tutorial ArchiveEnglish

Angular 2 architecture

Angular 2 architecture

An Angular 2 application is mainly composed of the following 8 parts:

The diagram below shows how each part works together:

overview

The templates in the diagram are composed of Angular-extended HTML syntax, component classes manage these templates, the application logic is handled by services, and then services and components are packaged in a module, finally starting the application through the root module.

Next, we will analyze the above 8 parts separately:


Module

A module is a piece of code that can be used to perform a simple task.

Angular applications are modular, and they have their own module system: NgModules.

Every Angular application should have at least one module (root module), which is usually named: AppModule.

An Angular module is a class with the @NgModule decorator, which receives a metadata object to describe the module's properties.

Several important properties are as follows:

A very simple root module:

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 start the application by bootstrapping the root module. The development process usually bootstraps AppModule in the main.ts file, as shown in the code below:

app/main.ts file:

import

{

platformBrowserDynamic

}

from

'

@angular/platform-browser-dynamic

'

;

import

{

AppModule

}

from

'

./app.module

'

;

platformBrowserDynamic

(

)

.

bootstrapModule

(

AppModule

)

;


Components

A component is a control class for a template used to handle the view part of the application and logic pages.

Components are the foundation and core of an Angular application and can be used throughout the application.

Components know how to render themselves and configure dependency injection.

Components interact with the view through an API composed of properties and methods.

There are three steps to create an Angular component:


Templates

The default language for Angular templates is HTML.

We can tell Angular how to display a component by using templates to define the component's view. Here is a simple example:

Original prompt (Chinese, left untranslated)



<div>

网站地址 : {{site}}

</div>

In Angular, double curly braces are used by default as interpolation syntax, and the value inside the braces is usually the name of a component property variable.


Metadata

Metadata tells Angular how to handle a class.

Consider the following situation: we have a component called Component, which is a class until we tell Angular it is a component.

You can attach metadata to this class to tell Angular that Component is a component.

In TypeScript, we use a decorator to attach metadata.

Instance

Original prompt (Chinese, left untranslated)



@Component({

   selector : 'mylist',

   template : '<h2>菜鸟教程</h2>'

   directives : [ComponentDetails]

})

export class ListComponent{...}

The @Component decorator can accept a configuration object and mark the following class as a component class.

Angular will create and display the component and its view based on this information.

Explanation of configuration items in @Component:


Data binding

Data binding provides a simple and consistent way to display data and data interaction, which is a mechanism for managing values within an application.

Through this mechanism, values can be retrieved from and assigned to HTML, making data reading, writing, and persistence operations simpler and faster.

As shown in the figure, there are four forms of data binding syntax. Each form has a direction—from DOM, to DOM, or two-way, as indicated by the arrows in the figure.

databinding

<h3> {{title}} <img src="{{ImageUrl}}"> </h3>

<img [src]="userImageUrl">

<button (click)="onSave()">Save</button>

<input [value]="currentUser.firstName" (input)="currentUser.firstName=$event.target.value" >


Directives

Angular templates are dynamic. When Angular renders them, it modifies the DOM based on directives.

A directive is a class with "directive metadata". In TypeScript, you attach metadata to a class using the @Directive decorator.

Angular includes the following three types of directives:



<li *ngFor="let site of sites"></li>

<site-detail *ngIf="selectedSite"></site-detail>

*ngFor tells Angular to generate a tag for each item in the sites list.

  • Tags.

    *ngIf means that the SiteDetail component will only be included when the selected item exists.


    Services

    In Angular2, a service is an independent module that encapsulates a specific function and can be used by others through injection.

    Services are divided into many types, including: values, functions, and features required by the application.

    For example, when duplicate code appears in multiple components, extract the duplicate code into a service to achieve code reuse.

    The following are some common services:

    • Logging Service
    • Data Service
    • Message Bus
    • Tax Calculator
    • Application Configuration

    The following instance is a logging service used to log to the browser console:

    
    
    export class Logger {
    
      log(msg: any)   { console.log(msg); }
    
      error(msg: any) { console.error(msg); }
    
      warn(msg: any)  { console.warn(msg); }
    
    }
    
    

    Dependency Injection

    Inversion of Control (IoC) is a design principle in object-oriented programming that can be used to reduce coupling between computer code. The most common way is called Dependency Injection (DI), and another way is called "Dependency Lookup".

    Through Inversion of Control, an external entity within a controlling system passes the reference of the object it depends on to an object when it is created. It can also be said that the dependency is injected into the object.

    In traditional development models, the caller is responsible for managing the dependencies of all objects, and circular dependencies have always been a nightmare. In the Dependency Injection pattern, this management is handed over to the Injector, which is responsible for replacing dependency objects at runtime, not at compile time. This characteristic of Inversion of Control, running injection, is the essence of Dependency Injection.

    Angular can determine which services a component requires by inspecting the parameter types of its constructor. For example, the SiteListComponent constructor requires a SiteService:

    
    
    constructor(private service: SiteService) { }
    
    

    When Angular creates a component, it first finds an Injector for the services required by the component.

    An Injector is a container that maintains service instances, storing previously created instances.

    If the requested service instance is not yet in the container, the Injector creates a service instance, adds it to the container, and then returns this service to Angular.

    After all services have been resolved and returned, Angular calls the component's constructor using these services as parameters. This is dependency injection.