Angular2 and Typescript

Source: Internet
Author: User
Tags export class

Angular2 and Typescript

Original link: Https://www.infoq.com/articles/Angular2-TypeScript-High-Level-Overview

Yakov Fain Posted on APR 26, 2016

--------------------------------------------------------------------------------------------------------------- ---------------

Angularjs is currently the most popular JavaScript framework available for creating Web applications. And now ANGULAR2 and typescript are making real-object-oriented development a mainstream way of web development, and syntactically similar to Java 8.

According to Brad Green, Google's engineering director, 1.3 million developers are using ANGULARJS and 300,000 developers are ready to start using ANGULAR2. After nearly 10 months of using ANGULAR2, I believe its impact on the JavaScript community will be comparable to the impact of the spring framework on the Java community.

In this article, I'll show you a brief overview of the ANGULAR2 framework.

At the end of 2014, Google announced that ANGULAR2 would completely rewrite the Angularjs and, in order to write ANGULAR2 applications, they even created a brand-new language "Atscript".

But at the same time, Microsoft has promised to increase its support for decorations (also called annotations) for their typescript language (a strict type of JAVASCRIPTZ superset language), which has created a new language for the development of the ANGULAR2 framework. And this is a recommended language for developing applications using the ANGULARJS framework.

You can, of course, use JavaScript (ECMASCRIPT5 and 6) and dart to develop angular 2 applications.

In addition, the angular team integrates another Microsoft Project into the ANGULAR2 framework-the RXJS library, an extended class library of native JavaScript.

ANGULAR2 is not an MVC framework, but a component-based framework. In the Angluar2 species, the application is a loosely coupled component tree.

For a chestnut, here's a sample landing page for an online auction app, which is the initial prototype of a navigation bar, a search box, a rotation display area, a product, and a combination of these components at the bottom.

The above image shows 3 product presentation components. Auto-rendering is done by binding an array of components to the template to fetch data from the server. The title of each product is a link to the Product Details page. Now that we want to design the auction system as a single-page application (SPA), we don't want to refresh the entire page in order to show the product details. Let's reuse the area now occupied by the rotation area and the product list, which can also be used to render product details while keeping the rest of the page intact. This task can be done in a few simple steps:

1. Use the angular routing-export command, which allows you to define the area occupied by the rotation zone and the product list as route exit so that it can change the content through the user's navigation bar.

2. Encapsulate the rotation zone and product components in the home page component

3. Create a new product detail component

4. Configure the angular route to display the home page or product detail component in a specific routing exit area.

We've talked a lot about components, but we haven't explicitly defined what a component is. In Typescript, a component is a simple class that is annotated by the @component keyword:

1 @Component ({2   selector: ' Auction-home ', 3   Template: ' 4     HTML or other markup are in-lined here 5   ' 6}) 7 Export Default class Homecomponent {8  9  //Application logic goes Here10}

@component annotations are used to define components and related metadata. In this example, the value of the Selector property defines the name of the HTML tag used to represent the component. The template property is a placeholder for HTML (or other) markup.

Back to our Auction landing page, the highest-level app component template should look something like this:

This template is a mix of standard and custom HTML tags, and custom HTML tags identify individual components. In the example we have arranged the HTML vertically. If we want to store the tag in a different file (in this case application.html), we can use the Templateurl property instead of the template property, and then the ApplicationComponent code will look like this:

Import {Component} from ' Angular2/core '; import {Route, Routeconfig, routeroutlet} from ' Angular2/router '; import Homecomponent from '. /home/home '; import navbarcomponent from '. /navbar/navbar '; import footercomponent from '. /footer/footer '; import searchcomponent from '. /search/search '; import productdetailcomponent from ". /product-detail/product-detail "; @Component ({  selector: ' auction-application ',  templateurl: ' app/ Components/application/application.html ',  directives: [    Routeroutlet,    navbarcomponent,    Footercomponent,    searchcomponent,    homecomponent  ]}) @RouteConfig ([  {path: '/', component: Homecomponent, as: ' Home '},  {path: '/products/:id ', component:productdetailcomponent, as: ' Productdetail '}]) Export default class ApplicationComponent {}

The ApplicationComponent class uses @component and @routeconfig, which are labeled URL-dependent content, for comment. The value of the Selector property is used to specify the user-defined HTML tag <auction-application>. The Templateurl property specifies the location of the marker. The section directive contains routing exits and all child components.

@RouteConfig note Two routes have been configured for the client navigation bar:

· The contents of a routed node named Home (Home page) are rendered by the Homecomponenet component and mapped to the URL fragment '/'.

· Routing nodes with the name Productdetail (product details) are mapped to the Productdetailcomponent component under the URL fragment '/product:id '.

When a user clicks on a specific product title, the contents of the default home routing node are replaced by the contents of the Productdetail routing node, which provides the value of the parameter ID and displays the product details in the routed exit area. For example, a link to navigate to the Productdetail routing node, with a product ID parameter and a value of 1234, can look like this:

<a [routerlink]= "['/productdetail ', {' prodId ': 1234}]" >{{product.id}}</a>

Dependency Injection

Components use services to implement business logic. A service is a class that is instantiated by angular and injected into a component.

Export class Productservice {  products:product[] = [];  GetProducts (): array<product> {    //the code to retrieve Product into goes here    return products;  }}

Now if you pass a variable of type Productservice to the constructor of Homecomponent in the form of a parameter, angular automatically instantiates and injects the service into the component:

@Component {...} Export Default class Homecomponent {  products:product[] = [];  Constructor (Productservice:productservice) {    this.products = productservice.getproducts ();  }}

Angular's dependency injection model is flexible and easy to use because objects are injected only through the constructor. The injector can form a layer (each component has an injector), and the injected object does not need to be implemented as a singleton mode at the application level because it defaults to Singleton, as in spring.

Inter-component communication

Inter-component communication can and should be implemented in a loosely coupled manner. A component can define input and output properties. To transfer data from a parent component to a child component, the parent component needs the value of the input property of the bound subcomponent. Subcomponents do not need to know who provided these values, it just needs to know how to use them.

If a component needs to transfer data to the outside world, it sends events out of the output properties. Sent to who? This component is out of the control. The component that is interested in the event creates a listener for the event of the custom component.

This mechanism allows us to think of components as black boxes, and we can pass values in or out. I recently recorded a video that might be useful to you, which demonstrates a way to implement a man-in-the-middle design pattern in Angular2.

Why use Typescript

Typescript is a superset of JavaScript, but it allows you to define new types like java. By defining variables by type, instead of still using the original var keyword as support for new tools back door, you will find this to be a huge productivity boost. Typescript brings a static code analyzer when you enter code into your recognizable Typescript editor (such as Webstorm/intellij idea,visual Studio code, Sublime text, and so on) The context-sensitive Smart hints feature directs you to pass a valid argument to the function, such as having the parameter use a valid object or type. If you accidentally use an incorrect type, the editor will highlight the wrong code. See how Webstorm supports typescript here.

Even if your Typescript app uses a third-party class library to write JavaScript, you can also set a type definition file (using the. d.ts suffix name) that contains the type definition for the class library. Hundreds of popular JavaScript class library type definition files are available for free and you can easily install them via typings, typings is a typescript definition management tool. Imagine that you want to use jquery (written in JavaScript) in your typescript code. The jquery type definition file contains all of the jquery's APIs definitions (containing types), so your IDE can prompt you what types to use or highlight the wrong code.

Performance and rendering

Rendering performance has been improved in the ANGULAR2 type of response. Most importantly, in fact, the rendering module is already in a separate module, which allows you to run code that is computationally large in the worker thread. You can access the Redraw Speed Challenge website to compare the rendering performance of each frame. You can feel the high-speed rendering of the huge data grids that are constantly being updated. Run the test case titled "DBMON Angular 2.0 beta-network worker", a grid of large amounts of data that constantly refreshes data (in separate threads) and quickly redraws in the browser.

If you want to ask what features make Angular2 stand out from other frameworks, the first bit that appears in my list will be a separate module for the partition that the template renders:

· Standalone template files with component interface definitions are processed through a separate renderer, which provides new opportunities for template optimization and precompilation, with the ability to create templates and render them on different devices.

· The Zone.js module listens for changes to the app and decides when to update the interface for each component. The triggering of any asynchronous event will re-validate the interface of each component and be fast and scary.

Note: For most applications, you do not need to know the internal workings of zone.js, but if your project requires optimized interface rendering for a complex application, you need to be prepared to set aside some time to learn more about the internal workings of the zone.

Keeping the rendering engine in a separate module and allowing the third-party class library to replace the renderer of the original DOM can achieve the goal of not relying on the browser platform. For example, allowing app code to be reused across devices, the interface renderer will use the native component in a mobile device. The code for the Typescript class does not need to be changed, but the content of the @component comment contains XML or other languages that will be used to render the native component. A custom ANGULAR2 renderer has been implemented in the Nativescript framework, which provides services like a bridge between JavaScript, native iOS, and Android interface components. By Nativescript You can reuse the code of the component, and all you need to do is replace the HTML in the template with XML. Another custom interface renderer allows the use of the angular 2 with React Native, a completely different approach to creating native (not Hybird) interfaces for iOS and Android systems.

Tool Set

Although ANGULAR2 's syntax and architecture are easier to understand than the Angularjs 1.X, Angular2 's toolset is more complex than the latter. That's not surprising, after all, you're writing code in one language and compiling it into another language, because everything will be compiled into JavaScript.

The Angular CLI is now a project that promises to provide a command-line interface that greatly simplifies individual processes, from initial project inception to production deployment.

Application debugging can be done in the editor or in the browser. We use Chrome's developer tools to debug. The source map generated by chrome allows you to debug Typescrip code while the browser is running JavaScript. This is also possible if you prefer to debug JavaScript, because the typescript translator generates JavaScript code, which allows others to read it directly.

Testing and Deployment

Angular2 comes with a test library that allows you to write test cases in the BDD format. Currently it supports only the Jasmine framework, but the support for more frameworks is already within reach. We use the Karma Test tool, which allows you to run different test cases separately for different browsers.

The Protractor framework allows you to write end-to-end test cases for your application. If you monitor your network when you load a simple application in development mode, you will see that the browser has downloaded more than 5 megabytes (half of which is the typescript compiler that the module loader uses, called SYSTEMJS). But with the deployment and optimization scripts running (we're using the Webpack Packaging tool), the size of this small application can be reduced to 160K (including the ANGULAR2 framework). We are looking forward to seeing how the angular CLI will implement the packaging capabilities of the production environment. The angular team is implementing the offline template compilation function, which reduces the size of the frame to around 50Kb.

Interface Component Library

When I write this article, there are a few interface component libraries that you can use in the ANGULAR2 application:

· Primeng-a library of ANGULAR2 interface components written by the creator of a primefaces (a very popular library used in the Java Service-side framework).

· Wijmo 5-A commercial Angular 2 interface component library. You need to purchase a developer certificate to use it.

· Polymer-a very beautiful and extensible component library developed by Google. In our company we have managed to create a ANGULAR2 pilot application using the Polymer component library, but there is room for improvement in the integration of the two.

· Material Design 2-a library of interface components that Google has developed specifically for ANGULAR2. The library is still in its infancy, but it's developing very quickly, and I'm looking forward to seeing a whole bunch of well-designed interface components in the next 3-4 months.

· Ng-lightning-a ANGULAR2 component and instruction library that was written in Typescript under the CSS framework of the Lightning design system.

Is it safe to use ANGULAR2 in an internal system?

Starting with the first beta release, we used ANGULAR2 in the Farata system to write a real-world project, and we didn't get into any big trouble, at least without the problem of finding a workaround.

If you want to be more insured, you can wait a few more months. Gossip says the RC version of ANGULAR2, which is likely to be a candidate version of the final product, will be announced at the Google i/0 conference in May 2016.

What will happen in the future?

In March 2016, Brad Green delivered a keynote speech at the Fluent conference through O ' Reilly. Take a look at the video of this presentation. Have you been touched? Anyway, I was touched.

About the author

Yakov Fain is a Java supporter who lives in New York and a partner of IT consulting Farata systems. He leads the Princeton jug organization, and he has written many articles and several books in the field of software development. Recently, he is working with people to create the book "Develop angular 2 with typescript", which is to be published in June 2016. Yakov often speaks at technical conferences, while also teaching Java and ANGULAR2 courses. His blog is yakovfain.com.

Angular2 and Typescript

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.