A brief summary of "heroic journey"----ANGULAR2 series (iii)

Source: Internet
Author: User
Tags emit export class

Objective:

This series introduces the basic concepts of zone.js and ANGULAR2 in the previous two articles. Then for NG2 's study, the official tour of Heroes began .

The following refining and personal understanding, of course, there will be incorrect places, please correct me. Interested friends, can start their own ng2 tour, and then combined with this article to understand.

NG2 configuration is troublesome, arbitrary introduction package may lead to some error, it is recommended to download the official quickStart directly.

Ng2 all the APIs into 7 types, when looking at the API, you can pay more attention to their type, easy to understand

@Component

@Component affirms an application-reusable UI component that can be instantiated by bootstrap or instantiated by itself directives properties.

/**/' @angular/core '; @Component  ({' app-component '),  Template: '<div>{{title}}</div> ') Export class appcomponent{  = ' Tour of Heroes ';}
/**/' @angular/platform-browser-dynamic './app.component ' Bootstrap (AppComponent)
// index.html<body>  <app-component></app-component>  </body>/*  * /<body>  <app-component> <div>tour of Heroes </div> </app-c Omponent>  </body>

@Component creates a shadow DOM for the component, loads the selected template into the Shadow DOM, and creates all the configured injection objects.

Bootstrap boot Run @component, the DOM is found based on the selector of @component, and a new sub-syringe is created, which is detected by a new zone instance.

Creates a shadow dom and loads it into the DOM node summary, instantiates the component, and finally initializes the supplied data.

Shadow DOM:

In the NG2 documentation, the shadow Dom is mentioned. You can refer to the article: Shadow DOM: Basics.

Shadow DOM allows Dom and CSS styles to be scoped, independent of each other, and style unaffected.
The browser's support for the Shadow Dom is not good, but ng2 in other ways, the function of similar shadow DOM is realized.

For example, when @component is configured with the Styles property, the style is loaded into the head when the component is instantiated

        


For example, our style is originally written with the H1 selector, and Ng is followed by a property selector [_ngcontent-hvh-1].
This property is also added to the root dom,ng of the component [_ngcontent-hvh-1].
With a property selector, Ng2 automatically isolates the scope of the style for us.

          

[_ngcontent-hvh-2] ...

@Input &@Output:

Creates a one-way input stream for component communication using the @input binding tag property. Need to introduce components: import {Input} from ' @angular/core ';

Example of "Heroic journey":

/*A*/Import {Input} from' @angular/core '; @Component ({selector:' Bank-account ', Template: ' Bank Name: {{bankname}} ' account Id: {{Id}} '}  Class BankAccount {@Input () bankname:string; @Input (' Account-id ') id:string; //This property was not bound, and won ' t was automatically updated by Angularnormalizedbankname:string;}/*B*/@Component ({selector:' App ', Template: ' <bank-account bank-name= ' RBC ' account-id= ' 4747 ' ></bank-account> ', directives: [ BankAccount]}) class App {} bootstrap (app);

A variable is declared using @input () in a class of a directive component, and the declared variable can be one-way data-bound through the properties of the instruction.

@Input has a parameter that binds the DOM's property name, as in the code above: @Input (' Account-id ') id:string;

The DOM property name Account-id and the ID variable of the class are bound,<bank-account account-id= "4747" >

Property names without parameters are defaulted with the variable name @Input () bankname:string; <bank-account bank-name= "RBC" >

This enables communication and binding between components.

In angular1, the attribute scope is defined in directive, which achieves data binding between scope scopes, similar to the @input function in Angular2

scope: {      "=",      "="}
<directive bank-name= "RBC" account-id= "4747" ></directive>
@Output the opposite of @input.

OnInit&constructor
OnInit和 constructor都能实现初始化时候执行,constructor is performed before Ngoninit. But their concepts are different.
Import {OnInit} from ' @angular/core '; Export class AppComponent implements oninit{    constructor () {         // Do something     }    ngoninit () {        //dosomething    }}

route:
配置路由,需要引入Routeconfig, Router_directives, Router_providers.
    • Routeconfig used to define the routing configuration
    • Router_directives provide instructions ([routerlink]<router-outlet>)
    • Router_providers Providing routing services
' @angular/router-deprecated '; @Component ({  ' My-app ',  Template: '      ,  directives: [Router_directives],  providers: [    router_providers,    heroservice  ]}) @ Routeconfig ([  {    '/heroes ',    ' Heroes ',    component:heroescomponent  }])

  [Routerlink] is used to specify the load link, which corresponds to the Name property of the @RouteConfig.

After the name is found, the route is modified and the corresponding UI component is displayed, which is eventually loaded into the <router-outlet> tab.

Using the Router-outlet,ui component will create the selector tag yourself and load the component under the Router-outlet tab.

      

Default routing & Routing parameters:

@RouteConfig ([    {        '/detail/:id ',// can be passed in this way        name: ' Herodetail ',        Component:componenta,         true // set the default route, and the error access address will access the default route     }])            
As above code: Componenta to receive parameters, you need to import Routeparams
Import {routeparams} from ' @angular/router-deprecated '; Routeparams is a Class,componenta initialization time,
Constructor (private routeparams:routeparams) is defined in the constructor or Ngoninit method body , using the This.routeParams.get (' ID ') for parameter acquisition.

Import {routeparams} from ' @angular/router-deprecated '; export class componenta{    constructor (private Routeparams:routeparams) {       Console.log ("ID:", this  . Routeparams.get (' id ')    }}}
To manually jump pages via router:

Import {Router} from ' @angular/router-deprecated ';

Class xxx{
Constructor (private router:router) {}
Go () {
This.router.navigate ([' Herodetail ', {id:this.id}]);//parameter 1 route name, Parameter 2 parameter
}
}


Event Bindings:

Binds an event stream to communicate between components.
Custom event Open, define an event open in component A, bind open with the Label property of "Component B", trigger by "component B"
//component a@component {    ' <b (open) = "open ($event)" ></b> '}class a{
Open () {
Console.log (' done ');
}
' @angular/core '; class b{@Output () Opennew eventemitter (); this. Open.emit (); // emit can also be used to pass the argument }
(open) = "open ($event)", the custom open method must take $event, otherwise it will not be executed, as for why later study.
If it is (click) This binding browser default event, (click) = "open ()", you can not pass $event.

Summary:

  when using NG2 or using TS-developed NG2, more code is written for declarations, dependencies, definition types, such as import, @Input, @Output, in the development of the time will feel very troublesome,

However, this strict specification brings about higher maintainability, such as import, although it may be a lot of writing, but later maintenance of a component can be very clear about the current component uses which modules.

When compiling, Angular2 follows strict patterns and can help avoid some code errors and non-specification.

This "heroic journey" is just the beginning, with a glimpse of the angular2 core, common APIs, organizational structure, and code style. There is a lot of content that needs to be developed and understood.

Although the involvement is not deep, but it has been obvious that some of the shortcomings in the ANGULAR1, in the Angular2 no longer exist.




A brief summary of "heroic journey"----ANGULAR2 series (iii)

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.