What is Angular 2? High level overview, feature and fundamentals.

来源:互联网 发布:java写hello world 编辑:程序博客网 时间:2024/06/07 02:51

原文链接: http://www.technicaldiary.com/angular-2-AngularJS-overview-feature-and-fundamentals/


What is Angular 2? High level overview, feature and fundamentals.

In our previous web page, the template of the top level Application Component might look like this:

angular-2-component-html-tag-technical--tech-diary

This template consists of a mix of standard and custom HTML tags which represent respective components. In the above example we in-lined the HTML. If we prefer to store the markup in a separate file (in this caseapplication.html), we would use the property template-URL instead of template, in this case: the code of the application component might look like this:

TypeScript
24 lines
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: 'technicaldiary-application',  templateUrl: 'app/components/application/technicaldiary.html',  directives: [    RouterOutlet,    NavbarComponent,    FooterComponent,    SearchComponent,    HomeComponent  ]})@RouteConfig([  {path: '/', component: HomeComponent, as: 'Home'},  {path: '/products/:id', component: ProductDetailComponent, as: 'ProductDetail'}])export default class AppComponent {}


The class AppComponent is annotated with @Component and@RouteConfig (for URL-dependent content). The value of the selector property will be used as a user-defined HTML tag <technicaldiary-application>. The templateUrl specifies the location of the markup. The section directives includes the RouterOutlet and all child components.

The annotation @RouteConfig configures two routes for the client-side navigation:

  • The content of the route named Home will be rendered by HomeComponent and mapped to the URL fragment /.
  • The content of the route named ProductDetail will be rendered  by ProductDetailComponent and mapped to the URL fragment /product:id.

When the user clicks on a particular product title, the content of the default Home route will be replaced with the content of the ProductDetail route, which provides the value of the parameter id and displays the product details in the <router-outlet> area. For example, the link for navigating to the ProductDetail route, that takes product id 1234 as a parameter, can look as follows:

<small><a [routerLink]="['/ProductDetail', {'prodId': 1234}]">{{ product.id }}</a></small>

Why typeScript?

TypeScript is a superset of JavaScript but like Java and C#, it allows you to define new types. Declaring variables with types rather than the genericvar opens the door to new tooling support, which you will find to be a great productivity enhancer. TypeScript comes with a static code analyzer, and as you enter code in your TypeScript-aware IDE (WebStorm/IntelliJ Idea, Visual Studio Code, Sublime Text, etc.) you’re guided by context sensitive help suggesting the available methods in the object or types of the function argument. If you accidentally use an incorrect type, the IDE will highlight the erroneous code. See how WebStorm supports TypeScripthere.

Even if your TypeScript application uses a third-party library written in JavaScript, you can install a type definition file (having the extension .d.ts), containing type declarations for this library. Type declarations for hundreds of popular JavaScript libraries are freely available, and you can easily install them with Typings, a TypeScript Definition Manager. Imagine that you want to use jQuery (written in JavaScript) from your TypeScript code. The type-definition files for jQuery will contain declarations (with types) of all jQuery APIs so your IDE can prompt you with which types to use, or highlight any erroneous code.

Dependency Injection in AngularJs 2

Components use services for implementing business logic. Services are just classes that Angular instantiates and then injects into components. Let’s define a service,

TypeScript
export class ProductService {  products: Product[] = [];  getProducts(): Array<Product> {    // The code to retrieve product into goes here    return products;  }}

Now if you specify an argument of type ProductService in the HomeComponent constructor, Angular will automatically instantiate and inject that service into the component:

TypeScript
10 lines

@Component{ ...}export default class HomeComponent {  products: Product[] = [];  constructor(productService: ProductService) {    this.products = productService.getProducts();  }}


Angular’s dependency injection module is flexible, and it is easy to use because the objects can be injected only via constructors. Injectors form a hierarchy (each component has an injector), and the injectable object doesn’t have to be an application-level singleton as it might by default in Spring.

Inter-component communications in Angular 2.

Component communication can and should be implemented in a loosely coupled manner. A component can declare input and output properties. To pass the data from a parent to a child component, the parent binds the values to the input properties of the child. The child has no need to know who provided the values; it just knows what to do with them.

If a component needs to pass the data to the outside world, it emits the events via the output property. Emits to whom? It’s none of the component’s business. Whoever is interested can create a listener to the custom component’s event.

This mechanism allows us to treat components as black boxes, that can get values in or send data out. I recently recorded ashort video you might find useful, illustrating one of the implementations of the Mediator design pattern in Angular 2.

Performance and Rendering of Angular 2

Rendering performance is substantially improved in Angular 2. Most importantly, the fact that the rendering module is located in a separate module allows you to run the computation-heavy code in a worker thread. Visitthe Repaint Rate Challenge Web site to compare the rendering performance of various frameworks. You can feel for yourself the high speed of rendering a large data grid with continuously updating data. Run the test titled “DBMON Angular 2.0 Beta – Web Workers”; a large data grid with constant data refreshes (in a separate thread) is repainted by the browser blazingly fast.

If you ask what Angular 2 features set it apart from other frameworks, first on my list would be this separate module for template rendering and zones:

  • Having the component’s UI declared in separate templates processed by an independent renderer opens up new opportunities in areas from optimization and precompilation of templates, to the ability to create templates for rendering on different devices.
  • The module zone.js monitors the changes in the application and makes decisions on when to update the UI of each component. Any async event triggers the revalidation of the UI in each component and it works amazingly fast.
Note:While for the majority of applications you won’t need to know the internals of zone.js, if your work on projects requiring fine tuning UI rendering in a complex application, you would be served well to allocate some time to learn more about the zone inner-workings.

Keeping the rendering engine in a separate module allows third-party vendors to replace the default DOM renderer with one that targets non browser-based platforms. For example, this allows reusing the application code across devices, with the UI renderers for mobile devices that use native components. The code of the TypeScript class remains the same, but the content of the @Component annotation will contain XML or another language for rendering native components. A custom Angular 2 renderer is already implemented in the  NativeScript framework, which serves as a bridge between JavaScript and native iOS and Android UI components. With NativeScript you can reuse the component’s code by just replacing the HTML in the template with XML. Another custom UI renderer allows to use Angular 2 with React Native, which is an alternative way of creating native (not hybrid) UI’s for iOS and Android.

Tooling in AngularJs 2

While the syntax and architecture of Angular 2 applications is a lot easier to understand than AngularJS 1.X, tooling is a bit more complex. This is not surprising; after all you are writing code in one language and deploying it in another, because everything is compiled to JavaScript.

Angular CLI is a project currently in the works that promises to provide a command line interface that will substantially simplify various processes, from initial project generation to production deployment.

Application debugging can be done either in the IDE or in the browser. We use Chrome Developer Tools for debugging. The generated source maps allow you to debug the TypeScript code while the browser runs JavaScript. If you prefer to debug JavaScript, it’s also possible because the TypeScript transpiler generates JavaScript that can be read by humans.

Testing and Deployment of Angular2

Angular 2 comes with a testing library that allows you to write unit tests in the BDD format. Currently it only supports the Jasmine framework, but additional framework support is on the way. We use Karma test runner, which allows tests to be run against various browsers.

The Protractor framework allows you to write end-to-end tests for your applications. If you monitor the network while loading a simple application in development mode you will see that the browser downloads more than 5Mb (half of that being the TypeScript compiler used by the module loader, SystemJS). But after running deployment and optimization scripts (we use the Webpack bundler), the size of a small app can be as little as 160K (including the Angular 2 framework). We’re looking forward to seeing how Angular CLI will implement production bundling. The Angular team works on offline template compilation, which will lower the framework’s overhead to 50Kb.

Conclusion

I hope you found Angular 2 is much interesting as you were expected. Angular 2.1.0 released on 12th Oct 2016 at the ng-conference. As new updates will come from ng-conference, we will update on this site (Technical Diary) with new tutorials and examples. If you  have questions or feeling there is something we should expand, please contribute in comments.


0 0
原创粉丝点击