Angular is a TypeScript-based open-source front-end platform that makes it easy to build web, mobile and desktop applications. The major features of this framework include declarative templates, dependency injection, end to end tooling which ease application development.
Angular is a popular open-source web application framework developed by Google. Its key features are:
Some key difference between AngularJS and Angular:
Feature | AngularJS | Angular |
---|---|---|
Architecture | Follows MVC (Model-View-Controller) architecture. | Follows MVVM (Model-View-ViewModel) architecture. |
Language | Written in JavaScript. | Written in TypeScript, a superset of JavaScript. |
Performance | Generally slower due to digest cycle and scope. | Generally faster with optimized rendering and change detection. |
Dependency Injection | Uses AngularJS's own DI system. | Utilizes a more advanced and standardized DI system. |
Mobile Development | Lacks native support for mobile development. | Supports mobile development through frameworks like Ionic. |
Tooling | Limited tooling compared to Angular. | Has a comprehensive CLI (Command Line Interface) for scaffolding, testing, and deployment. |
Angular Modules, also known as NgModules, are containers for different parts of an Angular application. They help in organizing the application into cohesive blocks of functionality. Every Angular app has at least one module, the root module.
Data binding is the automatic synchronization of data between the model and the view components. Angular supports both one-way and two-way data binding, enabling seamless interaction between the application logic and the UI.
Dependency Injection (DI) is a design pattern used in Angular to create and manage dependencies between different components or services. It helps in making components more modular, reusable, and easier to test.
Angular Routing is a mechanism for navigating between different views or pages in a single-page application. It allows developers to define routes and associate them with specific components, enabling the creation of a rich and dynamic user experience.
With Angular routing, we can:
Angular Directives are markers on a DOM element that tell Angular to do something to that element or its children. They can be classified into three types: component directives, structural directives, and attribute directives.
ViewChild is a decorator in Angular used to query and access child components, directives, or DOM elements from within a parent component. It allows parent components to interact with their children and access their properties or methods.
Angular Forms and Form Validation are features provided by the Angular framework to facilitate the creation and validation of HTML forms within web applications.
Angular Forms: Angular supports two types of forms: template-driven forms and reactive forms.
Form Validation: Angular provides built-in mechanisms for form validation to ensure that user input meets certain criteria before it is submitted. Form validation can be performed both on the client-side (in the browser) and on the server-side.
Angular Interpolation is a way to bind expressions in Angular templates. It uses double curly braces to evaluate expressions and display their results in the HTML template.
HttpClient is a built-in Angular module that provides a simplified API for making HTTP requests to web servers. It supports features like request and response interception, error handling, and progress events.
An Angular Service is a TypeScript class that encapsulates reusable functionality and provides it to other parts of the application. Services are used to share data, perform common tasks, and maintain state across different components.
Angular Pipes are a feature that allows you to transform data in your templates before displaying it to the user. They are used to format data, apply filters, and perform other transformations such as currency conversion or date formatting.
Angular Testing involves writing and executing tests to ensure that Angular applications behave as expected. It helps in identifying and fixing bugs, improving code quality, and maintaining application reliability over time.
Angular Guards are interfaces that allow developers to implement logic to control navigation in an Angular application. They are used to protect routes, perform authentication, and enforce access control based on certain conditions.
Here are some of the major difference between AngularJS and Angular:
AngularJs | Angular |
It is based on MVC architecture | This is based on the Service/Controller |
It uses JavaScript to build the application | Uses TypeScript to build the application |
Based on the controller concept | This is a component-based UI approach |
Difficult to build SEO-friendly application | Fully supports mobile platforms |
Difficult to build SEO-friendly application | Ease to build SEO friendly applications |
Angular has the key components below,
Directives add behaviour to an existing DOM element or an existing component instance.
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
Now this directive extends HTML element behavior with a yellow background as below
<p myHighlight>Highlight me!</p>
Components are the most basic UI building block of an Angular app, which form a tree of Angular components. These components are a subset of directives. Unlike directives, components always have a template, and only one component can be instantiated per element in a template. Let's see a simple example of Angular component.
import { Component } from '@angular/core';
@Component ({
selector: 'my-app',
template: ` <div>
<h1></h1>
<div>Learn Angular6 with examples</div>
</div> `,
})
export class AppComponent {
title: string = 'Welcome to Angular world';
}
Modules are logical boundaries in your application, and the application is divided into separate modules to separate the functionality of your application. Let's take an example of app.module.ts root module declared with @NgModule decorator as below,
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule ({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
providers: []
})
export class AppModule { }
The NgModule decorator has five important (among all) options:
Angular application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application. The representation of lifecycle in pictorial representation as follows,
The description of each lifecycle method is as below,
Data binding is a core concept in Angular and allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data. There are four forms of data binding(divided as 3 categories) which differ in the way the data is flowing.
<li>Name: </li>
<li>Address: </li>
<input type="email" [value]="user.email">
<button (click)="logout()"></button>
<input type="email" [(ngModel)]="user.email">
Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators.
Angular CLI(Command Line Interface) is a command line interface to scaffold and build angular apps using nodejs style (commonJs) modules. You need to install using below npm command,
npm install @angular/cli@latest
Below are the list of few commands, which will come handy while creating angular projects
Angular Dependency Injection Tree is a hierarchical structure that Angular uses to manage the dependencies between different parts of an application. It ensures that each component or service gets the correct instance of its dependencies when it is instantiated.
Angular Universal is a technology that allows developers to render Angular applications on the server side. It enables better performance, improved SEO, and support for progressive web apps (PWAs) by pre-rendering pages on the server before sending them to the client.
Angular Schematics are templates or blueprints used by the Angular CLI to generate code for components, modules, services, and other Angular artifacts. They help in automating repetitive tasks and enforcing consistent project structures and coding standards.
Angular Lazy Loading is a technique used to load parts of an application on-demand, instead of loading everything upfront. It improves application startup time and reduces initial bundle size by loading modules asynchronously when they are needed.
Angular Material is a UI component library for Angular applications that provides a set of pre-built, customizable components following Google's Material Design guidelines. It includes components like buttons, cards, forms, and navigation elements.
NgRx is a state management library for Angular applications based on the Redux pattern. It helps in managing application state in a predictable and immutable way by centralizing state in a single store and using actions and reducers to modify it.
Angular uses hierarchical injectors to manage dependencies across multiple modules. Each Angular application has a root injector, and every NgModule has its own injector. Angular creates a tree of injectors based on the module hierarchy, ensuring that components and services get the correct instances of their dependencies.
The Angular Compiler is responsible for translating Angular components and templates into JavaScript code that can be executed by the browser. It performs Ahead-of-Time (AOT) compilation, which compiles components and templates during the build process rather than at runtime, resulting in faster startup times and improved performance.
Angular Elements allow you to package Angular components as custom elements (web components) that can be used in non-Angular applications or frameworks. They provide a way to share Angular components across different projects or integrate them into existing applications without requiring a full Angular environment.
Angular CLI (Command Line Interface) is a command-line tool for initializing, developing, and maintaining Angular applications. To create a new Angular project using Angular CLI, you can use the command:
ng new my-project
This command creates a new Angular project named "my-project" with the default project structure and configuration.
Angular directives are instructions in the DOM that Angular uses to manipulate the behavior of elements. There are three types of Angular directives: Angular directives are instructions in the DOM that Angular uses to manipulate the behavior of elements.
There are three types of Angular directives:
Angular TestBed is a utility provided by Angular for configuring and creating instances of Angular testing modules. It provides methods for configuring modules, components, services, and other dependencies in a test environment. TestBed is used in Angular testing to set up the testing environment, inject dependencies, and create component instances for testing.
Angular Dependency Injection is a design pattern used to manage the dependencies between different parts of an Angular application. It allows components and services to request dependencies from a container rather than creating them directly. The benefits of Angular Dependency Injection include:
Angular NgZone is a service provided by Angular for managing the execution context of asynchronous operations in Angular applications. It is used to explicitly run code outside or inside Angular's zone, which determines when change detection is triggered. NgZone is used to optimize performance and ensure that certain operations are executed within Angular's change detection cycle.
Angular ViewEncapsulation is a mechanism for encapsulating the styles of Angular components to prevent them from affecting other parts of the application. There are three modes of ViewEncapsulation in Angular:
Angular Services are TypeScript classes that encapsulate reusable functionality and provide it to other parts of the application. They are used for implementing business logic, data access, and other common tasks. Services are different from components in that they are not associated with a specific view or UI element. They are singleton instances that are shared across the application and can be injected into components or other services.
Angular Route Guards are interfaces that allow developers to control navigation to and from Angular routes. There are several types of Angular Route Guards:
Angular ng-content is a directive used to project content into a component's template. It allows developers to create reusable components with customizable content slots. ng-content is used within a component's template to define where the projected content should be inserted. It supports various projection modes, such as selecting content based on CSS selectors or providing default content.
Angular Observables are a powerful tool for handling asynchronous operations in Angular applications. They represent streams of data that can be observed over time. Observables are used for handling asynchronous tasks such as HTTP requests, event handling, and data streaming. They support a wide range of operators for transforming, filtering, and combining data streams.
Angular ElementRef is a class that provides access to the underlying native element of a component or directive in Angular. It is used to interact directly with the DOM elements within Angular templates. ElementRef is commonly used in conjunction with ViewChild to access DOM elements from within component classes and perform operations such as styling, manipulation, or event handling.
Angular Template-driven Forms and Reactive Forms are two approaches for handling forms in Angular applications:
Angular Guards are interfaces that allow developers to implement logic to control navigation to and from Angular routes. They are implemented as classes that implement one of the guard interfaces such as CanActivate, CanActivateChild, CanDeactivate, or Resolve. Angular Guards are then registered in the application's route configuration to control access to specific routes or route components.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
// Check if user is authenticated
const isAuthenticated = true; // Replace with your authentication logic
if (!isAuthenticated) {
this.router.navigate(['/login']); // Redirect to login page if not authenticated
return false;
}
return true; // Allow navigation if authenticated
}
}
Angular Pipes are a feature that allows you to transform data in your templates before displaying it to the user. Angular provides several built-in pipes for common transformations such as formatting dates, numbers, and currency, as well as for filtering and sorting arrays. Additionally, you can create custom pipes to perform custom transformations specific to your application's requirements.
NgRx is a state management library for Angular applications based on the Redux pattern. It provides a centralized store for managing application state in a predictable and immutable way. NgRx works by maintaining the application state as a single immutable object, using actions to describe state changes, and using reducers to specify how those actions modify the state. It also provides features such as effects for handling side effects and selectors for querying the store.
Angular Forms provide a way to handle user input and perform form validation in Angular applications. Forms in Angular can be template-driven or reactive, and they support features such as two-way data binding, validation,
Angular Animation enables adding dynamic motion and effects to elements in Angular apps. Implemented through Angular's animation library, it allows declarative animation definitions using CSS keyframes and JavaScript, enhancing user experience with smooth transitions and visual feedback.
Angular Content Projection allows components to accept and render dynamic content. Developers define slots in component templates with `<ng-content>`, enabling users to inject content into these slots, promoting reusability and flexibility in component development.
Angular Change Detection is the process of detecting changes in the application's data and updating the user interface accordingly. It works by comparing the current state of data to its previous state, triggering updates to the DOM as needed to reflect those changes.
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<p></p>
<button (click)="changeMessage()">Change Message</button>
`
})
export class ExampleComponent {
message: string = "Hello, world!";
changeMessage() {
this.message = "Goodbye, world!";
}
}
Angular Routing facilitates navigation between different parts of a single-page app without full page reloads. Lazy loading of modules defers loading non-essential parts until requested, optimizing app performance by reducing initial load time.
Angular Pipes transform data in templates before display. They're applied with the pipe operator (|). Built-in pipes format dates, numbers, and text, while custom pipes enable custom transformations. Pipes are implemented in templates using the pipe operator and can be built-in or custom-defined.
<!-- Template -->
<p></p>
// Component
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<p></p>
`
})
export class ExampleComponent {
today: Date = new Date();
}