What are the eight main construction blocks of Angular 2 applications and angular application structures?

Source: Internet
Author: User
Tags export class

What are the eight main construction blocks of Angular 2 applications and angular application structures?

Previous words: I recently read quickstart on the official website during Angular 2 and National Day, and wrote an article, just a hello world demo. Later, I continued to read a project tutorial of it. At the beginning, I was able to keep up with it, and it was quite confusing. Indeed, it is difficult for new users to understand a framework. So stop the project and start to see how angular's overall framework works. Contact the project and analyze it.

Link: Chinese official website

Body start:

Angular applications: Use HTML Write templates with angular extension syntax, manage these templates with component classes, add application logic with services, and package and publish components and services in modules. Start the application by guiding the root module. Angular takes over and presents the application content in the browser, and responds to user interaction according to the operation instructions we provide.

These terms are very important and run through angular application development.

Eight main construction blocks of angular applications:

Module modules
Component components
Template
Metadata
Data binding
Directive ctive ve
Services
Dependency injection

Module

Angular applications are modular and have their own module systems called angular modules/NgModules.

What is the module? What does modularity mean in angular?

An angular application has at least one module (the root module), which is called the AppModule.

Most applications have many other feature modules, which are formed by a group of domain classes, workflows, or closely related functions.

All angular modules are classes with @ NgModule decorators.

Angular modules are class !!!

The modifier is a function used to modify JavaScript classes. Attaches metadata to the class.

NgModule is a decorator function that receives metadata objects used to describe module attributes. Attributes:

Declarations (Declaration): View class in this module. Angular has three view classes: components, commands, and pipelines.
Exports: a subset of declarations, which can be used as component templates in other modules.
Imports: class to be exported from other templates in this module component template.
Providers: the creator of the service. This module adds them to global service tables so that they can be accessed in any part of the application.
Bootstrap: identifies the main view (root component) of the application ). Only the root module can set this attribute.

The following is a simple root module:

// App. module. tsimport {NgModule} from '@ angular/core'; import {BrowserModule} from' @ angular/platform-browser'; // @ NgModle annotator function, which accepts an object, the object has several attributes: @ NgModule ({imports: [BrowserModule], providers: [Logger], declarations: [AppComponent], exports: [AppComponent], bootstrap: [AppComponent]}) // export the export Statement of AppComponent. The root module does not need to be exported, and other components do not need to be imported to the root module. Export class AppModule {}

Boot the root module to start the application. Bootstrap the AppModule in the main. ts file:

// App/main. tsimport {platformBrowserDynamic} from '@ angular/platform-browser-dynamic'; // from app. the module file has imported AppModuleimport {AppModule} from '. /app. module '; platformBrowserDynamic (). bootstrapModule (AppModule );

In this case, the project only contains the app/app. module. ts file and app/main. ts file. The former defines the root module of the application, and the latter references it to start the application.

Comparison between Angular and JavaScript modules:

The modularization of JavaScript is file-based import, and each file is a module.

Angular module (class decorated with @ NgModule) is the basic feature of Angular.

The JavaScript module system manages a set of JavaScript objects.

In JavaScript, each file is a module, and the objects defined in this file belong to this module. The export keyword can be used to declare some of its objects as public. Other modules can use the import Statement to access public objects.

This feature of JavaScript is very useful.
The export keyword is declared public, and the import Statement accesses the public object.

These two types are used in Angular, as shown in the preceding two files.

Module library

As mentioned above, Angular uses the JavaScript module, so its JS module is the library module and JS file library.

The Angular library names are all prefixed with @ angular. you can install them using the npm package management tool and access the objects in them using the preceding import Statement.

Angular is a single page framework implemented by JS, so it still needs a wide range of JS libraries.
For example, import the Component modifier from the @ angular/core library:

Import {Component} from '@ angular/core ';

Use the JavaScript Import Statement to import certain Angular modules from the Angular library.

Import {BrowserModule} from '@ angular/platform-browser ';

In the code of the above root module, the application module needs some materials of the BrowserModule, so it is added to the imports of the @ NgModule metadata:

Imports: [BrowserModule];

Let's take a look at the basic JS modules in the @ angular Library:

Common
Compiler
Core
Forms
Http
Platform-browser
Platform-browser-dynamic
Router
Upgrade

Therefore, Angular and JavaScript modular systems are used at the same time.

The imports and exports are messy. You can sort them out by yourself.

Components

The component controls a small part of the screen, that is, the view.

Define the application logic of the component in the class (used to support the view ). Components interact with views through APIS consisting of attributes and methods.

Therefore, components are associated with the view.

The previous export keyword can declare the class in the module as public, and then implement access in the import.

There are many attributes and methods in the class.

Template

You can define a view by using the template that comes with the component. Templates exist in the form of HTML, which tells Angular how to render components (Views ).

View the template of a component file:

// app/hero-list.component.html

The template looks like standard HTML, which contains some non-standard HTML syntax. * NgFor, {hero. name}, {click}, [hero], and

Therefore, Angular processes HTML in this way.

Metadata

Metadata tells Angular how to process a class.

The export class has some methods and attributes. But how can this class be handled?

By attaching metadata to this class, this class is a component.

In TypeScript, we use decorator to append metadata.

Analyze the following metadata:

// app/hero-list.component.ts@Component({ moduleId: module.id, selector:  'hero-list', templateUrl: 'hero-list.component.html', providers: [ HeroService ]})export class HeroListComponent implements OnInit {/* . . . */}

@ Component the decorator marks the class that follows it as a Component class.

The class after the decorator will be converted into a component class?

Configuration items in the decorator:

ModuleId:Provide the base address for the URL related to the module.
How do I use this address?
Selector:CSS selector, which tells Angular to find a tag in the parent HTML, and then create a component instance and insert the tag.
HTML display.
TemplateUrl:The relative address of the module of the component HTML template.
Set the location of the HTML template.
Providers:Array, containing the dependent injection Provider required by the service that the component depends on. Tells Angular that the constructor of this component requires a service, and the component can from the service.
Some data is transmitted through services. Otherwise, other views can only control static display.

The metadata in @ Component tells Angular how to obtain the metadata you set for the Component.

Templates, metadata, and components depict this view.

A component is a view. A template provides HTML structure.

Data Binding

If there is no framework, we need to do everything. Push the data value to the HTML control and convert the user feedback to the action and value update display. You can use jQuery to implement this process.

Angular framework implements data binding, a mechanism that allows each part of the template to interact with each other. Add the binding tag to the template HTML. Angular connects the template and component.

This means that we automatically update the View data because it is bound to a component and can associate the data.

Let's look at an example:

// app/hero-list.component.ts<li>{{hero.name}}</li>

It is observed that there are some non-standard HTML characters in the template HTML.

{Hero. name} interpolation expression: displays the value of the hero. name attribute of the component in the element. [Hero] property binding: transfers the value of the parent component to the hero attribute of the Child component. (Click) event binding: Call A method when a user clicks an element.

The relationships between files need to be sorted out clearly. Two-way data binding: both property binding and event binding are supported. Example:

// app/hero-detail.component.ts<input [(ngModel)]="hero.name">

The value of the data property is transmitted from the component with the property bound to the input box. The event binding allows the user to modify the property to be sent back to the component and set the property value to the latest value.

Command

Angular templates are dynamic. When Angular renders them, it modifies the DOM according to the instruction.

That is to say, when parsing the template HTML, the commands will be parsed.

An instruction is a class with metadata.

A command is a class that contains command source data.

In TypeScript, you need to use the @ Directive modifier to append metadata to the class.

Similar to the metadata of the previous class, the @ Component modifier attaches the metadata to the following class and programming Component class. This is to append some metadata to the subsequent instruction class through the @ Directive modifier.

Structured commands:Modify the layout by adding, removing, and replacing elements in the DOM. NgFor and ngIf.

Attribute command:Modifies the appearance or behavior of an existing element. NgModel

Service

There are many types of services, including the features required by values, functions, and applications.

Almost everything can be a service. A typical service is a class.

For example:

Log Service
Data Service
Message Bus
Tax Calculator
Application configuration

Components are the largest service consumers.

Some operations of components require the Service to provide some data.

For example, display the log records in the browser console:

// app/logger.service.tsexport class Logger { log(msg: any)  { console.log(msg); } error(msg: any) { console.error(msg); } warn(msg: any) { console.warn(msg); }}

These services enable the component to retrieve data from the server for verification ......, All of this can be done through the service.

The task of components is to provide user experience. That's all!

It is between a view (rendered by a template) and an application logic (including a model.

Well-designed components provide attributes and methods for data binding and delegate unimportant tasks to the service.

Dependency Injection

Dependency injection is a method for providing new instances of classes and is responsible for handling all dependencies (services) required by classes ).

Angular uses dependency injection to provide services required by the components and components we need.

Angular can view the parameter types of constructor to view the services required by the component.

Example:

// app/hero-list.component.tsconstructor(private service: HeroService) { }

The constructor parameter mentions a service.

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

The injector is a container for maintaining service instances and stores previously created instances. If there is no requested service instance in the container, the injector creates a service instance, adds it to the container, and then returns the service to Angular. When all services are parsed and returned, Angular calls the component constructor with these services as parameters, which is dependency injection.

That is to say, the service is executed before the component. It first processes all the services to a warehouse, and then processes the components. The service that the component needs will be retrieved from the warehouse for you.
The provider adds the module to the root module, and uses the same instance of the service wherever it is:

// app/app.module.tsproviders: [ BackendService, HeroService, Logger],

The provider is the component that must exist before determining the processing component
You can also register it to the component layer:

// app/hero-list.component.ts@Component({ moduleId: module.id, selector:  'hero-list', templateUrl: 'hero-list.component.html', providers: [ HeroService ]})

Add to the attributes of the decorator metadata.

Key Points of dependency injection:

1. Dependency injection permeate the entire Angular framework
2. the injector is the core of the mechanism.
The injector maintains a container and stores the created service instances.
The injector can use the provider to create a new service instance.
3. the provider is a formula used to create services.
4. register the provider with the injector.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.