ANGULAR2 Self-study Note (ii)---eight major structural blocks

Source: Internet
Author: User
Tags export class

Angular's idea: always delegate data access to a supportive service class.

Angular application: Use the Angular extension syntax to write HTML templates, use component classes to manage these templates, add application logic with services, and package publishing components and services with modules.

We start the app by booting the root module. Angular takes over, displays the content of the app in the browser, and responds to the user's interactions based on the instructions we provide.

Eight major building blocks of the ANGULAR2:
Modules (module)
Components (component)
Templates (Template)
Meta data (metadata)
DataBinding (data binding)
Directive (Directive)
Services (Service)
Dependency Injection (Dependency injection)

One. Module
The Angular application is modular, and Angular has its own modular system, which is called the Angular module or ngmodules.
Each Angular application has at least one module (the root module), which is customarily named Appmodule.
The root module may be the only module in some small applications, and most applications will have many feature modules, each of which is a cohesive block of code focused on an application area, workflow, or tightly related functionality.
The Angular module (either a root module or an attribute module) is a class with a @ngmodule adorner.
Adorners are functions that are used to modify JavaScript classes. Angular has many adorners that are responsible for attaching metadata to classes to understand the design intent of those classes and how they should work.


Ngmodule is an adorner function that receives a metadata object that is used to describe the properties of a module. The most important of these properties are:

Website Explanation:
Imports-the component templates declared by this module require other modules that are part of the class.
Declarations-Declares the view class that is owned in this module. Angular has three view classes: components, directives, and pipelines.
A subset of exports-declarations that can be used for component templates in other modules.
Providers-the creator of the service and joins to the Global Services list, which can be used to apply any part.
Bootstrap-Specifies the application's main view (called the root component), which is the host of all other views. Only the root module can set the Bootstrap property.

Understand:
Imports: Importing other modules, which is the ability to use other modules, must be imported.
Declarations: declares, declares what this module contains. Some students may encounter, define a directive, used in the component but always do not have the issue of effective, first we have to check is whether the declaration.
Exports: externally visible content. is equivalent to those declared as public in. Net.
Providers: A service provider that is used primarily to define services. It is estimated that the NG2 framework automatically checks registered services into dependent injection instances, as is currently the case for testing.
Bootstrap: Boot module. Used only in the root module. Modules other than the root module are not available.


eg

 Import {ngmodule} from   "  @angular/core  "  ;import { Browsermodule}  from   "  @angular/platform-browser  "   class  appmodule {} 

The export statement of the

Appcomponent is used only to demonstrate how it is exported, which is not required in this example. The root module does not need to export anything, because other components do not need to import the root module.


Angular module vs. JavaScript module
JavaScript also has its own modular system for managing a set of JavaScript objects. It is completely different and completely unrelated to the Angular module system. In
JavaScript, each file is a module, and all objects defined in the file are subordinate to that module. With the Export keyword, a module can declare some of its objects to be public. Other JavaScript modules can access these common objects by using the import statement.

Introduced: import {JavaScript module name} from ' File relative path ';  
         The adorner component needs to be introduced from the ANGULAR2 library before using the adorner     import  {Component} from ' @angular/core ';
         Import angular module from angular: import {browsermodule} from ' @angular/ Platform-browser ';

         Two systems are easier to confuse and share the same vocabulary "imports" and "exports".

Definition: Export class module name {JavaScript code block}


Two. The component
component is responsible for controlling a small area of the screen, which we call a view. The

* * Component defines the application logic for the component in the class and provides support for the view. Components interact with the view through a number of APIs that consist of properties and methods.

class Herolistcomponent implements OnInit {  heroes:hero[];  Selectedhero:hero;  Constructor (private  service:heroservice) {}  Ngoninit () {    this]  . Service.getheroes ();  }   this. Selectedhero = hero;}}

Lifecycle Hooks: angular creates, updates, and destroys components as users roam through the app. Insert your own actions at various points in the component life cycle, such as the Ngoninit () declared above. Life hooks also need to be introduced in advance import {OnInit} from ' @angular/core ';


Three. Templates

The template can use any custom component and native HTML, template syntax (*ngfor, {{hero.name}}, (click), [Hero]);



Four. Metadata: Metadata tells Angular how to handle a class

The top component herolistcomponent is actually a class that wants to change the class into a component, which requires metadata to be added to the class, and in Typescript, we use the adorner (decorator) to append the metadata.

@Component ({  moduleId:module.id,  selector:    'hero-list',   ' hero-list.component.html ' ,  providers:  class  Herolistcomponent implements OnInit {  /* */}

@Component adorners can accept a configuration object, and Angular creates and presents components and their views based on that information.

The @Component configuration items include:
ModuleID: Provides the base address for a module-related URL (for example, Templateurl).
The selector:css selector, which tells Angular to find Templateurl: Module relative address of the component HTML template, as shown earlier.
Providers: A dependency injection provider for a component's required service, Angular: The component's constructor requires a heroservice service so that the component can get heroic data from the service.

The metadata inside the @Component tells Angular where to get the main building blocks you specified for the component. Templates, metadata, and components depict this view together.
Other meta-data decorators are in a similar way to guide the behavior of Angular. For example, @injectable, @Input, and @output are some of the most commonly used adorners. This architecture is handled by adding metadata to your code so that Angular knows what to do.


Five. Data binding

There are four forms of data binding syntax.
Bind to DOM: [prototype]= "Value"; (even) = "Handle"
Bind to Dom: {{Vlue}}
Two-Way binding: [(Ng-module)]= "property";

eg
The {{hero.name}} interpolation expression displays the value of the component's Hero.name property in the <li> tag.
The [Hero] property binding passes the Selectedhero value of the parent component herolistcomponent to the hero attribute of the child component Herodetailcomponent.
The (click) event binding invokes the Selecthero method of the component when the user clicks on the hero's name.
<input [(Ngmodel)]= "Hero.name" > Bidirectional data Binding: Data property values are streamed from the component to the input box through property binding. User's modifications are streamed back to the component via an event binding, and the property value is set to the most recent value

Angular handles all data bindings in each JavaScript event loop, starting at the root of the component tree and recursively processing all subcomponents.


Six. Directive: Angular template is dynamic. When Angular renders them, it transforms the DOM according to the operation provided by the instruction.

The difference between a directive and a template:
An instruction is a class with "instruction metadata". In TypeScript, the metadata is appended to the class through the @directive adorner. A component is a directive with a template, and the @Component adorner is actually a @directive adorner, just extending some of the template-oriented features.

There are also two other types of directives: structured directives and attribute (attribute) directives.
1. Structured directives: Modify the layout by adding, removing, and replacing elements in the DOM.
<li *ngfor= "Let Hero of Heroes" ></li>

2. Attribute-type directives: modifies the appearance or behavior of an existing element. In templates, they look like standard HTML attributes.
The Ngmodel directive is an example of a property-based directive that implements two-way data binding. Ngmodel Modify the behavior of an existing element (typically <input>): Set its Display property value and respond to the change event.
<input [(Ngmodel)]= "Hero.name" >

3. Custom directives: As above, Herolistcomponent is a custom directive


Seven. Service:

An example of a service class that records to Console.log:

class Logger {          log (Msg:any)   {console.log (msg);}          Error (Msg:any) {console.error (msg);}          Warn (Msg:any)  {console.warn (msg);}        }

By passing data to the background and returning data through a received promise:

ExportclassHeroservice {PrivateHeroes:hero[] = []; Constructor (PrivateBackend:backendservice,PrivateLogger:logger) {} getheroes () { This. Backend.getall (Hero). Then ((heroes:hero[]) = {               This. Logger.log (' fetched ${heroes.length} heroes. ');  This. Heroes.push (... heroes);//Fill Cache            }); return  This. Heroes; }        }

The Getheroes () and Addhero () methods of the service return the observable object of a hero's data observable the data is obtained by angularhttp from the server. We can see the observable object observable as a stream of events published by some "source". By subscribing to the observable object observable, we listen to events in this stream. In these subscriptions, we specify how to act when a WEB request generates a success event (payload is Hero data) or failure event (payload is the wrong object).

The component itself does not obtain data from the server, does not validate input, and does not write logs directly to the console. They delegate these tasks to the service.
The task of a component is to provide a user experience. It is between the view (rendered by the template) and the application logic (which usually includes some concepts of the model). Well-designed components provide properties and methods for data binding and entrust other chores to the service. The application logic is split into services and used by dependency injection to use these services in the component.

Eight. Dependency Injection:
Dependency injection is a way to provide a new instance of a class, and it is also responsible for handling all the dependencies required for a good class. Most of the dependencies are services. Angular uses dependency injection to provide the services required for new components and components.
Angular knows what services the component needs by looking at the parameter types of the constructor. For example, the constructor for the Herolistcomponent component requires a Heroservice service:
Constructor (private Service:heroservice) {}
When Angular creates a component, it first requests an injector (injector) for the service required by the component.

Process of Dependency Injection:
The injector maintains a container for a service instance that holds the previously created instance. If the requested service instance is not in the container, the injector creates a service instance, adds it to the container, and returns the service to angular. When all the requested services are parsed and returned, angular invokes the component's constructor with these services as parameters.

Register Heroservice provider Provider in the injector before requiring injection of heroservice. Provides a commercial to create and return a service, usually the service class itself.
We can register a provider in a module or component. The provider is typically added to the root module to use the same instance of the service anywhere.

Providers: [          backendservice,          heroservice,          Logger        ],

It can also be registered at the component layer in the providers attribute in the @component metadata, indicating that each new instance of the component will have a new instance of the service.

@Component ({          moduleId:module.id,          selector:    'hero-list',           ' hero-list.component.html ' ,          providers:  [Heroservice]        })

The key points to remember about dependency injection are:
The dependency injection penetrates throughout the Angular framework and is used everywhere.
INJECTOR (INJECTOR) is the core of this mechanism.
The injector is responsible for maintaining a container to hold the service instance it has created.
The injector can use the provider to create a new service instance.
A provider is a recipe for creating a service.
Register the provider with the injector.

ANGULAR2 Self-study Note (ii)---eight major structural blocks

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.