angular2.0-components

Source: Internet
Author: User

Until now, ANGULAR2.0 completed its alpha-32 version of the development, the new version is still in the iterative development, the problem is that each version of the previous version will have some changes, including the API changes, which will lead to many versions based on the previous version of the demo will not work, and its official web-based tutorials are The previous version did not change in time, this resulted in even if according to the official website of the tutorial to write run may also get unexpected results, in this case, this article uses the latest more stable angular alpha-31 version to reconstruct its official website step by step Guide, and as a basis, Describes the components in ANGULAR2.

Component is a trend in the software development process, it is based on packaging technology, focus on reducing the coupling degree of software module development, in the traditional back-end language development has been very good implementation and development, such as Microsoft's COM components. In web development, so far, there is no one component technology that can be natively supported and widely used by browsers. At present, the website has developed the Web Components specification, Shadow DOM as a key technology to implement the specification is also in the continuous development. Unfortunately, the current browser support is not good, far from the actual widespread use of a long distance. So at present the more famous solution is Google's polymer and Mozilla's X-tag, they allow a part of the modern browser can encapsulate the custom user components, and let the component is independent of the client JS, that is, the client JS can not be modified or manipulated the elements inside the component, Custom components are represented externally as a whole. This is like the HTML5 video tag, you just need to put a video tag on the page, it can be rendered by the browser as a playback screen and playback control bar, even if you look at the original code in the Developer tool, you can see a video tag and not be able to see its internal implementation. External JS can only control its behavior through a limited API, and it renders the same effect on different pages regardless of the original style of the page. This is the Web component.

Angular2.0 is exactly the same idea to design the entire framework, it can be said Angular2.0, the component is its core concept. As mentioned earlier, since browsers are not currently able to provide native support for Web components, angular from a framework perspective to address this issue. The purpose of this article is to explain how to implement a component in Angular2.0.

I uploaded a seed project on GitHub for future learning of Angular2.0 in order to quickly demonstrate the effects and eliminate the environmental build-up process. This article is based on this project, step by step to understand the concept of components.

Step one, clone the seed project to a local

Create a folder locally to make a Git clone action in that folder

git clone https://github.com/myzhibie/ng2-demo.git

The second step, the local global installation Gulp (if already installed, can save this step)

Install -G gulp

Step three, install all dependencies for the project in the project root directory

Install

This step may require FQ if the failure is generally a network cause.

If all of the above steps are successful, you can already run the seed project.

Gulp Play

In the original seed project, the SRC folder already has all the code in this article as a reference, you can delete them completely (except index.html and style.css) and create them yourself.

1. Create a simple component

Create a display.js file under the SRC folder (strictly speaking TS file, because this article is based on the typescript script, of course you can also use ES5,ES6 to write the entire project, but compared to typescript more complex, ANGULAR2 official tutorial is also used Preferred typescript script, visually with the push of ANGULAR2, Microsoft's typescript will fire AH), used to write the logic of the component, and in HTML with the following code reference it

System.import (' Display ');

In index.html, add a line of HTML code

< Display ></ Display >

This means that a display component has been customized.

Then go to Display.js and write the following logic

1Import {componentannotation as Component, viewannotation as View, bootstrap,ngfor,ngif} from ' Angular2/angular2 ';2 3 class Friendservice {4Names:array<string>;5 Constructor () {6          This. names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];7     }8 }9 @Component ({TenSelector: ' Display ', One hostinjector:[Friendservice] A }) - @View ({ -Templateurl: ' showdata.html ', the Directives:[ngfor,ngif] - }) - class Displaycomponent { - myname:string; +Names:array<string>; - Constructor (friendservice:friendservice) { +          This. Myname= ' Myzhibie '; A          This. names=Friendservice.names; at     } - Updateitems (name:string) { -         This. Names.push (name); -     } - donetyping ($event) { -         if($event. which===13){ in              This. Updateitems ($event. target.value); -$event. target.value=NULL; to         } +     } - } the  *Bootstrap (displaycomponent);

The first line of code first introduces Component,view,bootstrap, and ngfor,ngif several core directives, and line 3rd to 8th defines an external service, Similar to the service in angular1.x, some common methods or code can be abstracted into a service, and then injected in the way component in the call, in terms of thinking, this and angular1.x no difference, but the specific definition of the way has changed greatly, Ang ULAR2 is defined using the Class keyword, and the structure is clear. The service has a names property that is a string array type and is initialized in the constructor. The code 9 through 12 defines the configuration item associated with the component, and the Selector property is a selector that selects which DOM element the component corresponds to on the HTML page. The Hostinjector property indicates that the Friendservice is injected into this component, which is the way to ensure a dependency injection that runs in the Angular2 alpha31 version, and the official web site gives Appinjector, That is the configuration property of the previous version of Di.

The code 13-16 line defines the component view-related configuration, templateurl represents its corresponding template file, is showData.html.directives represents the built-in directive that can be used in its template, here we choose Ngfor and Ngif, The former is used for circulation, the latter is used for judgment, and the specific usage is given in showdata.html.

The 17th to 33rd line of code is to define a complete component, and you will find that it is a class, not the type of controller in angular1.x, in fact, the class of the component is its controller, which is more elegant and concise. The 20-23 row is the constructor for this component, which initializes its properties, where the names property is passed through the Friendservice object of the dependency injection. At the same time, two methods are defined in the controller, Updateitems is used to add a new names item, and the Donetyping method is used to process the input tag in the component by pressing ENTER to add the names entry after the input is completed. Here's what showdata.html.

1 <P>Friends</P>2         <ul>3             <Li*ng-for= "#name of Names">4 {{name}}5             </Li>6         </ul>7         <input#nametext (KeyUp)= "donetyping ($event)">8         <Button(click)= "Updateitems (nametext.value)" >Additems</Button>9         <Pclass= "P2"*ng-if= "Names.length > 3">You have many friends</P>

The 3rd to 6th line is a ul inside added Li, through the ng-for instruction Loop (similar to 1 in the Ng-repeat) its controller in the names property, note that the call command when the front to add * indicates that this is a Angular2 built-in instructions, while using # To define a local variable in the loop, and line 4th uses {{}} to bind the variable. Line 7th is an input tag that defines a nametext local variable that can be referenced elsewhere in the page. It is important to note that you cannot define Nametext or Name-text, both of which will be converted in Angular2, without a definite result, and I believe this issue will be resolved in the subsequent official release. Also, register an onkeyup event with the input tag to point it to the Donetyping method in its controller, and its parameter $event represents the event object. Line 8th registers an onclick event with the button tag whose arguments refer to the value of the input tag above by the local variable Nametext. The 9th line in the P tag is specified in Ng-if, if the controller's names length is greater than 3 to display the P label, otherwise it will not be displayed.

Run the above code with the following results:

You can add an li by writing a value in input to the Click button, or by using the ENTER key.

2. References between components

With the exercise above, we know how to define a component and bind it to events in response to a user request, which is actually defining a complete component, but a Web reference is not a component that can handle it. Angular2.0 allows you to refer to other components in a custom component in a simpler way, that is, a reference between components.

Add a line of code to the first index.html

< Parent ></ Parent >

Indicates that this is a parent component and then adds a parent.js file with the following writing logic:

1Import {componentannotation as Component, viewannotation as View, bootstrap,ngfor,ngif} from ' Angular2/angular2 ';2 3 @Component ({4Selector: ' Parent '5 })6 7 @View ({8Template: ' 

,9 Directives:[childcomponent]Ten }) One class Parentcomponent { A message:string; - Constructor () { - This. message= ' Parent component '; the } - } - - @Component ({ +Selector: ' Child ' - }) + A @View ({ atTemplate: ' <p class= ' pchild ' >{{message}}</p> ' - }) - - class childcomponent{ - message:string; - Constructor () { in This. message= ' Child component '; - } to } +Bootstrap (parentcomponent);

Line 3rd to 16th of the code is used to define the parent component, line 18th to 31st defines a subcomponent childcomponent, note the 第8-9 line, and the reference between the components is a placeholder for the Insert component in the View annotation template <child></ Child>, and then references its class name in directives. This completes the invocation of the component, in which case a "stacked wood" approach can be used to build our web application, and it improves the code reuse rate. The results of the operation are as follows:

The review element results are as follows:

As can be seen from the above, Angular2.0 for the definition and use of components compared to angular1.x is more simple and elegant, learning curve is more angular1.x flat.

Original Code Address Https://github.com/myzhibie/ng2-demo

angular2.0-components

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.