📜 ⬆️ ⬇️

AngularJS vs Angular 2: key differences

We in the Web Development team of Itransition already have a good development experience on Angular 2 and want to share it.

This article is aimed at those cool guys who are developing on Angular and are thinking of switching to the second version.

Should I start a new project on Angular 2?


Definitely - yes! And that's why:
')

Start a new project


Finally, a breath of fresh air, complete freedom, you can start from scratch. Thoroughly work through the architecture, data structure, components, various abstractions, create a dictionary of application terms, and so on. That everything was beautiful.

the freedom of action


But with the first version of Angular is not so simple. It is necessary that everything invented lay on the realities of the framework, its modules and services of a strictly defined type. You can’t just create and accurately create a class or component that will do something important. Need to decide what this component will be in terms of the framework? What type of service: “value”, “constant” or still “factory”? Or maybe a service like “service”? After all, it creates an object with the operator new, as if this is what you need. What if singleton is not enough? And these questions arise almost always, working with Angular, in such situations, and there is no definite answer to them.

The lack of such restrictions on the part of the framework, in my opinion, is a strong advantage of Angular 2. You can use any convenient modular system, arbitrarily call and connect arbitrary code.

Code generator


Next to start working on the project it is necessary:


With the second version of the framework, we get a command line tool with which you can generate applications, modules, components, directives, services, filters (pipe - their new name), run tests, check code, etc. And to perform the above, you need to run one command:

ng new app-name 

All the necessary infrastructure in the best at the moment performance will be created. Immediately you can get to work. Nothing extra.

The command may take additional arguments. For example, if you plan to use the Stylus CSS preprocessor:

 ng new app-name --style=styl 

Compilation and assembly of styles will be automatically adjusted according to the selected preprocessor.

TypeScript


The generated application code will use TypeScript, which scares many, most likely simply because of erroneous ideas about it. This is actually the same JavaScript (ECMAScript 6), but with some nice and useful gadgets:


All this allows you to write more stable and beautiful code, eliminates the need to everywhere use nasty JSDoc.

Having started using TypeScript, I want to write only on it, and you no longer understand how it was possible to be so sinful - not to use it before?

Components


In Angular 2 there are no controllers, only components. You can create a new one like this:

 ng generate component playground/player 

This command will create a player directory in the playground with the minimum required component code:

  1. implementation file
  2. template file
  3. style file with extension used by CSS preprocessor,
  4. unit test file.

No copy-paste - the source of evil and mistakes! The generated implementation code for the component will be as follows:

 import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-player', templateUrl: './player.component.html', styleUrls: ['./player.component.styl'] }) export class PlayerComponent implements OnInit { constructor() {} ngOnInit() {} } 

@ + Component here - and there is an example decorator. Ultimately, this is a simple function that takes as its argument the constructor defined below and modifies it with the configuration described, in this case it is:

  1. selector - defines what the component element will be called in the application templates (<app-player> </ app-player>),
  2. templateUrl - the path to the file template of the current component,
  3. styleUrls - an array of paths to the component style files.

In addition to the listed parameters, there are others that allow you to write template code and styles in the same file, configure the encapsulation of styles of this component, etc.

Two-way binding


The key feature of Angular is two-way binding. How is it implemented in Angular 2?

 <app-player [(position)]="playerPosition"></app-player> 

Such an entry in the template will pass the value of the playerPosition property of the current component and will change it when the position property inside the player component changes. This is two-way binding.

But why such a weird record?

Angular 2 has a new syntax that allows you to pass property values ​​to child components (one-way binding). It uses square brackets:

 <app-player [position]="playerPosition"></app-player> 

And you can subscribe to events that occur in child components. Parentheses are used:

 <app-player (positionChange)="onPositionChange($event)"></app-player> 

Such an entry implies that the player component has a positionChange property, which is an instance of the EventEmitter class. And when this.positionChange.emit (newValue) is called in the player component, the onPositionChange ($ event) code specified in the template is executed. $ event will contain the value of newValue.

Actually, this is how Angular 2 implements two-way binding:

  1. passing the property's original value,
  2. subscription to the event with the name “property name inside the child component” + “Change”,
  3. property change in the parent component when an event occurs.

And the [(position)] = “playerPosition” entry is only syntactic sugar, which does everything described automatically and saves time on building a house, planting a tree and growing a son.

Thanks to this implementation in Angular 2, there are no watchers who were previously sources of many performance problems. Now everything is more natural.

SOLID principles


In our team, we actively use the principles of SOLID, which make support and further development of the application a more efficient and enjoyable process.

Angular 2 solves many problems associated with a high level of code connectivity, a new powerful implementation of Dependency Injection, and the ability to abstract from implementations of various interrelated components using interfaces (TypeScript).

For example, you can write the following structure:

 class SomeComponent { constructor(public someService: SomeService) {} } 

And when creating an instance of this component, an instance of the SomeService service will be automatically created and transferred to the SomeComponent constructor. This greatly reduces the level of connectedness and allows you to test them separately from each other.

Also, the public someService (TypeScript) entry makes this service available within an instance of a class using the keyword this (this.someService).

Validation of forms


Template-based validation, which was previously, remains, but a new additional implementation has appeared. Its configuration is fully implemented in JavaScript, which allows you to create a set of rules dynamically, create reusable validators and fully manage the process, including filtering user input.

An example of the implementation of the form for entering a new password with the verification of its complexity and confirmation:

 let passwordControl = new FormControl('', [ Validators.required, CustomValidators.complexPassword, ]); let passwordConfirmControl = new FormControl('', [ Validators.required, ]); this.formGroup = new FormGroup({ password: passwordControl, passwordConfirm: passwordConfirmControl, }, CustomValidators.match(passwordControl, passwordConfirmControl)); 

A validator (Validators.required and the like) is a simple function to which a value is passed and which returns null or an object with a description of the error.

In the form template, you must specify the formGroup:

 <form [formGroup]="formGroup"> 

Input fields need to specify the appropriate formGroup control names:

 <input type="password" formControlName="password"> <input type="password" formControlName="passwordConfirm"> 

And that's all. Whether the form is valid, all errors and states can be obtained through the formGroup object, which will be updated each time a user interacts with it.

Routing


Routing is similar to the former, but with some nice improvements. For example, if some cumbersome application module is rarely used, you can load it dynamically:

 { path: 'profile', loadChildren: 'app/profile/prodile.module#ProfileModule' } 

Processing all requests starting with / profile (/ profile / photo, / profile / orders, / profile / orders /: id) will be passed to ProfileModule, which will be downloaded once the first need.

Low threshold of entry


At the beginning of the article spoke about the low threshold of entry. Despite the power of Angular 2, this is true.

In my opinion, this is due to the fact that:


But this does not mean the ease of his mastering by a person who does not know JavaScript.

Conclusion


You can also write a lot about the new version of the framework, compare the main services, figure out how to work with asynchronous operations (Zone.js), mention reactive programming (Rx.js) and so on. But it will not be an article, but a whole book.

I want to say that Angular 2 is a very professional and high-quality framework. Working with him, you feel that he was written by people who have extensive experience in practical development and you understand that you no longer want to write on his first version.

→ QuickStart

Successes!

Source: https://habr.com/ru/post/320014/


All Articles