Home > Web Front-end > JS Tutorial > AngularJS and Angular 2 : a Detailed Comparison

AngularJS and Angular 2 : a Detailed Comparison

William Shakespeare
Release: 2025-02-15 09:00:13
Original
171 people have browsed it

AngularJS and Angular 2 : a Detailed Comparison

The main differences between AngularJS and Angular 2

This article compares the main differences between the first generation AngularJS and Angular 2. If you are currently using an AngularJS project and are not sure if you should migrate, this article will help you get started. In recent years, Angular has developed rapidly as a framework and platform for developing single-page applications (SPA) and progressive web applications (PWA).

AngularJS is the concept of building views based on declarative programming. This requires decoupling DOM operations from the business logic of the application, which has many benefits in itself. However, AngularJS has many shortcomings in terms of performance and how it works at the bottom. So the development team spent a year rewriting the code from scratch and released Angular 2 in late 2016. Most developers consider Angular 2 to be a different platform that has little resemblance to the original AngularJS. Let's compare and compare AngularJS and Angular 2.

Framework Architecture

AngularJS follows the traditional MVC (model-view-controller) architecture, including models, views and controllers:

  • Controller: Handles user interaction, binding models and views.
  • View: Represents the presentation layer and the actual UI.
  • Model:Abstract representation of data.

Some developers believe that AngularJS follows the MVVM pattern and replaces the controller with a view model. The view model is a JavaScript function similar to a controller. What makes it special is that it synchronizes the data between the view and the model. Changes made to UI elements are automatically propagated to the model and vice versa. The following figure shows how various AngularJS components are connected together.

AngularJS and Angular 2 : a Detailed Comparison

Angular adopts a component-based architecture. Each Angular application has at least one component called the root component. Each component has a related class that handles business logic and a template representing the view layer. Multiple closely related components can be stacked together to create modules, each module itself forming a functional unit.

AngularJS and Angular 2 : a Detailed Comparison

As you can see in the figure, the component is bound to the template. Components are composed using TypeScript classes and attach templates to them using @Component annotation. Services can be injected into components using Angular's dependency injection subsystem. The module concept in Angular is very different from the AngularJS module. NgModule is a container that defines functional units. NgModule can contain components, services, and other functions. Module units can then be imported and used with other modules.

Template

In AngularJS, templates are written in HTML. To make it dynamic, you can add AngularJS-specific code such as properties, tags, filters, and form controls. In addition, it supports the aforementioned two-way data binding technology. The following code snippet demonstrates the use of directives and double braces in a template:

<div ng-app>
  <div ng-controller="MyController">
    <input ng-model="foo" value="bar"></input>
    <button ng-click="changeFoo()">{{buttonText}}</button>
  </div>
  <🎜>
</div>
Copy after login
Copy after login

In Angular, the template structure of AngularJS has been improved and many new features have been added to the template. The main difference is that each component has a template attached. All HTML elements work in the template except <script>, <style>, <base>, and <title>. In addition, there are also functions such as template binding, template interpolation, template statements, attribute binding, event binding and two-way binding. Built-in attribute instructions (such as NgClass, NgStyle, and NgModel) and built-in structure instructions (such as NgIf, NgForOf, NgSwitch) are also part of the template.

Dependency injection

Dependency injection is a design pattern that is responsible for satisfying dependencies and injecting them into components when needed. This avoids the need to hardcode dependencies into components. AngularJS has an injector subsystem that is responsible for creating components, injecting dependencies, and parsing a list of all dependencies. The following components can be injected as needed:

  • value
  • factory
  • service
  • provider
  • constant

Services, instructions and filters can be injected using factory methods. Here is an example of a factory method. The factory method is registered with a module named myModule:

angular.module('myModule', [])
.factory('serviceId', ['depService', function(depService) {
  // ...
}])
.directive('directiveName', ['depService', function(depService) {
  // ...
}])
.filter('filterName', ['depService', function(depService) {
  // ...
}]);
Copy after login

Although the method remains the same, Angular has a new dependency injection system that is different than the old DI mode. Angular's dependency injection is managed through an array of @NgModule that contains providers and declarations. The declarations array is the space for declaring components and instructions. Dependencies and services are registered through providers array.

Suppose you have a service that retrieves a contact list called ContactlistService and provides it to the ContactList component. You first need to register the ContactlistService in the app.module.ts array in providers. Next, you need to inject the service into the component as follows:

import { Component }   from '@angular/core';
import { Contact }        from './contact';
import { ContactListService } from './contactlist.service';

@Component({
  selector: 'app-contacts-list',
  template: `
    <div *ngFor="let contact of contacts">
      {{contact.id}} - {{contact.name}} - {{contact.number}}
    </div>
  `
})
export class ContactListComponent {
  contacts: Contact[];

  constructor(contactlistService: ContactListService) {
    this.contacts = contactlistService.getcontacts();
  }
}
Copy after login

Here, we tell Angular to inject services into the component's constructor.

JavaScript vs TypeScript

AngularJS is a pure JavaScript framework. The models in AngularJS are ordinary old JavaScript objects. This makes the entire project setup process much easier. Any developer with some basic JavaScript experience can start using the framework. Because of this, Angular 1.0's learning curve is very smooth compared to other front-end frameworks.

Angular 2 introduces TypeScript as the default language for building applications. TypeScript is a syntax superset of JavaScript, compiled into ordinary JavaScript. The Angular team chose TypeScript over JavaScript because of the type annotation feature, which allows you to perform optional static type checking. Type checking prevents compile-time errors from sneaking into your code that might otherwise be ignored. This makes your JavaScript code more predictable.

In addition, TypeScript is also popular for its classes, interfaces, and decorators (class decorators, attribute decorators and parameter decorators). Angular uses the TypeScript class to define components. @Component is a popular example of how to attach metadata to a component using a class decorator. Typically, this includes component configuration details such as template selector tags, templateUrl, and providers arrays so that you can inject any related dependencies into the component:

<div ng-app>
  <div ng-controller="MyController">
    <input ng-model="foo" value="bar"></input>
    <button ng-click="changeFoo()">{{buttonText}}</button>
  </div>
  <🎜>
</div>
Copy after login
Copy after login

Tool support

Better tool support helps developers build things faster and add them to the overall development workflow. For example, the command line interface (CLI) can greatly reduce the time it takes to create an application from scratch. Similarly, there are other tools like IDE, text editor, test kit, etc. that can help you make development easier.

AngularJS does not have an official CLI, but there are many third-party generators and tools available. For IDE, WebStorm and Aptana are popular choices among developers. If you are like me, you can customize a normal text editor like Submlime Text Editor and add the correct plugin to it. AngularJS has a browser extension for debugging and testing called ng-inspector. AngularJS structure allows for accessibility to third-party modules. You can find all the popular ng modules on ngmodules.org, an open source project for hosting AngularJS modules.

Angular has more tool support than AngularJS. There is an official CLI that allows you to initialize new projects, serve them, and build optimized packages for production. You can read the Angular CLI on GitHub for more information. Because Angular uses TypeScript instead of JavaScript, Visual Studio is supported as an IDE. That's not all. There are also many IDE plug-ins and standalone tools that can help you automate and speed up certain aspects of your development cycle. Augury for debugging, NgRev for code analysis, Codelyzer for code verification, etc. are all very useful tools.

Summary

AngularJS has many flaws—mostly performance-related—but it used to be the go-to choice for rapid prototyping. However, it makes no sense to return to AngularJS now or maintain AngularJS project. If you haven't migrated yet, you should consider doing so.

In this article, we introduce the five main differences between AngularJS and Angular 2. Almost everything except template structure and dependency injection methods have been improved. Many popular Angular 1.0 features, such as controllers, scopes, instructions, module definitions, etc., have been replaced by other alternatives. In addition, the underlying language has been changed and the structure has been modified.

AngularJS and Angular FAQs (FAQs)

(The FAQ part is omitted below because it is too long and does not match the pseudo-original requirements. The FAQ part can be optionally retained or reorganized as needed, and pseudo-original processing such as synonyms are replaced.)

The above is the detailed content of AngularJS and Angular 2 : a Detailed Comparison. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template