Angular
Click on the star icon to add the question to your favorites. Found an issue? Let us know.
Angular is a TypeScript-based open-source front-end platform that makes it easy to build applications with in web/mobile/desktop. The major features of this framework such as declarative templates, dependency injection, end to end tooling, and many more other features are used to ease the development.
Angular is a completely revived component-based framework in which an application is a tree of individual components.
Some of the major difference in tabular form
AngularJS | Angular |
---|---|
It is based on MVC architecture | This is based on Service/Controller |
This uses use JavaScript to build the application | Introduced the typescript to write the application |
Based on controllers concept | This is a component based UI approach |
Not a mobile friendly framework | Developed considering mobile platform |
Difficulty in SEO friendly application development | Ease to create SEO friendly applications |
TypeScript is a typed superset of JavaScript created by Microsoft that adds optional types, classes, async/await, and many other features, and compiles to plain JavaScript. Angular built entirely in TypeScript and used as a primary language. You can install it globally as
npm install -g typescript
Let's see a simple example of TypeScript usage,
function greeter(person: string) {
return "Hello, " + person;
}
let user = "Sudheer";
document.body.innerHTML = greeter(user);
The greeter method allows only string type as argument.
Angular has the below key components,
- Component: These are the basic building blocks of angular application to control HTML views.
- Modules: An angular module is set of angular basic building blocks like component, directives, services etc. An application is divided into logical pieces and each piece of code is called as "module" which perform a single task.
- Templates: This represent the views of an Angular application.
- Services: It is used to create components which can be shared across the entire application.
- Metadata: This can be used to add more data to an Angular class.
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 formed a tree of Angular components. These components are subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an 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>{{title}}</h1>
<div>Learn Angular6 with examples</div>
</div> `,
})
export class AppComponent {
title: string = 'Welcome to Angular world';
}
In a short note, A component(@component) is a directive-with-a-template.
Some of the major differences are mentioned in a tabular form
Component | Directive |
---|---|
To register a component we use @Component meta-data annotation | To register directives we use @Directive meta-data annotation |
Components are typically used to create UI widgets | Directive is used to add behavior to an existing DOM element |
Component is used to break up the application into smaller components | Directive is use to design re-usable components |
Only one component can be present per DOM element | Many directives can be used per DOM element |
@View decorator or templateurl/template are mandatory | Directive doesn't use View |
A template is a HTML view where you can display data by binding controls to properties of an Angular component. You can store your component's template in one of two places. You can define it inline using the template property, or you can define the template in a separate HTML file and link to it in the component metadata using the @Component decorator's templateUrl property.
Using inline template with template syntax,
import { Component } from '@angular/core';
@Component ({
selector: 'my-app',
template: '
<div>
<h1>{{title}}</h1>
<div>Learn Angular</div>
</div>
'
})
export class AppComponent {
title: string = 'Hello World';
}
Using separate template file such as app.component.html
import { Component } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "app/app.component.html"
})
export class AppComponent {
title: string = "Hello World";
}
Modules are logical boundaries in your application and the application is divided into separate modules to separate the functionality of your application. Lets 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
- The imports option is used to import other dependent modules. The BrowserModule is required by default for any web based angular application
- The declarations option is used to define components in the respective module
- The bootstrap option tells Angular which Component to bootstrap in the application
- The providers option is used to configure set of injectable objects that are available in the injector of this module.
- The entryComponents option is a set of components dynamically loaded into the view.
Angular application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application. The description of each lifecycle method is as below,
- ngOnChanges: When the value of a data bound property changes, then this method is called.
- ngOnInit: This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
- ngDoCheck: This is for the detection and to act on changes that Angular can't or won't detect on its own.
- ngAfterContentInit: This is called in response after Angular projects external content into the component's view.
- ngAfterContentChecked: This is called in response after Angular checks the content projected into the component.
- ngAfterViewInit: This is called in response after Angular initializes the component's views and child views.
- ngAfterViewChecked: This is called in response after Angular checks the component's views and child views.
- ngOnDestroy: This is the cleanup phase just before Angular destroys the directive/component.
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.
- From the Component to the DOM:
Interpolation: {{ value }}: Adds the value of a property from the component
<li>Name: {{ user.name }}</li>
<li>Address: {{ user.address }}</li>
Property binding: [property]=”value”: The value is passed from the component to the specified property or simple HTML attribute
<input type="email" [value]="user.email">
- From the DOM to the Component:
Event binding: (event)=”function”: When a specific DOM event happens (eg.: click, change, keyup), call the specified method in the component
<button (click)="logout()"></button>
- Two-way binding:
Two-way data binding: [(ngModel)]=”value”: Two-way data binding allows to have the data flow both ways. For example, in the below code snippet, both the email DOM input and component email property are in sync
<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
Class decorators, e.g. @Component and @NgModule
import { NgModule, Component } from "@angular/core"; @Component({ selector: "my-component", template: "<div>Class decorator</div>" }) export class MyComponent { constructor() { console.log("Hey I am a component!"); } } @NgModule({ imports: [], declarations: [] }) export class MyModule { constructor() { console.log("Hey I am a module!"); } }
Property decorators Used for properties inside classes, e.g. @Input and @Output
import { Component, Input } from "@angular/core"; @Component({ selector: "my-component", template: "<div>Property decorator</div>" }) export class MyComponent { @Input() title: string; }
Method decorators Used for methods inside classes, e.g. @HostListener
import { Component, HostListener } from "@angular/core"; @Component({ selector: "my-component", template: "<div>Method decorator</div>" }) export class MyComponent { @HostListener("click", ["$event"]) onHostClick(event: Event) { // clicked, `event` available } }
Parameter decorators Used for parameters inside class constructors, e.g. @Inject, Optional
import { Component, Inject } from "@angular/core"; import { MyService } from "./my-service"; @Component({ selector: "my-component", template: "<div>Parameter decorator</div>" }) export class MyComponent { constructor(@Inject(MyService) myService) { console.log(myService); // MyService } }
In Angular8, the CLI Builder API is stable and available to developers who want to customize the Angular CLI
by adding or modifying commands. For example, you could supply a builder to perform an entirely new task, or to change which third-party tool is used by an existing command.
TypeScript classes has a default method called constructor which is normally used for the initialization purpose. Whereas ngOnInit method is specific to Angular, especially used to define Angular bindings. Even though constructor getting called first, it is preferred to move all of your Angular bindings to ngOnInit method. In order to use ngOnInit, you need to implement OnInit interface as below,
export class App implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
//called after the constructor and called after the first ngOnChanges()
}
}
A service is used when a common functionality needs to be provided to various modules. Services allow for greater separation of concerns for your application and better modularity by allowing you to extract common functionality out of components.
Let's create a repoService which can be used across components,
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
@Injectable({
// The Injectable decorator is required for dependency injection to work
// providedIn option registers the service with a specific NgModule
providedIn: "root" // This declares the service with the root app (AppModule)
})
export class RepoService {
constructor(private http: Http) {}
fetchAll() {
return this.http.get("https://api.github.com/repositories");
}
}
The above service uses Http service as a dependency.
Dependency injection (DI), is an important application design pattern in which a class asks for dependencies from external sources rather than creating them itself. Angular comes with its own dependency injection framework for resolving dependencies( services or objects that a class needs to perform its function).So you can have your services depend on other services throughout your application.
The AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted. When a new value is emitted, the pipe marks the component to be checked for changes.
Let's take a time observable which continuously updates the view for every 2 seconds with the current time.
@Component({
selector: "async-observable-pipe",
template: `<div><code>observable|async</code>: Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
time = new Observable((observer) =>
setInterval(() => observer.next(new Date().toString()), 2000)
);
}
You can store your component's template in one of two places. You can define it inline using the template property, or you can define the template in a separate HTML file and link to it in the component metadata using the @Component decorator's templateUrl property. The choice between inline and separate HTML is a matter of taste, circumstances, and organization policy. But normally we use inline template for small portion of code and external template file for bigger views. By default, the Angular CLI generates components with a template file. But you can override that with the below command,
ng generate component hero -it
We use Angular ngFor directive in the template to display each item in the list. For example, here we iterate over list of users,
<li *ngFor="let user of users">
{{ user }}
</li>
The user variable in the ngFor double-quoted instruction is a template input variable
Sometimes an app needs to display a view or a portion of a view only under specific circumstances. The Angular ngIf directive inserts or removes an element based on a truthy/falsy condition. Let's take an example to display a message if the user age is more than 18,
<p *ngIf="user.age > 18">You are not eligible for student pass!</p>
Note: Angular isn't showing and hiding the message. It is adding and removing the paragraph element from the DOM. That improves performance, especially in the larger projects with many data bindings.
Angular recognizes the value as unsafe and automatically sanitizes it, which removes the script tag but keeps safe content such as the text content of the script tag. This way it eliminates the risk of script injection attacks. If you still use it then it will be ignored and a warning appears in the browser console. Let's take an example of innerHtml property binding which causes XSS vulnerability,
export class InnerHtmlBindingComponent {
// For example, a user/attacker-controlled value from a URL.
htmlSnippet = 'Template <script>alert("0wned")</script> <b>Syntax</b>';
}
Interpolation is a special syntax that Angular converts into property binding. It’s a convenient alternative to property binding. It is represented by double curly braces({{}}). The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property. Let's take an example,
<h3>
{{title}}
<img src="{{url}}" style="height:30px">
</h3>
In the example above, Angular evaluates the title and url properties and fills in the blanks, first displaying a bold application title and then a URL.
A template expression produces a value similar to any Javascript expression. Angular executes the expression and assigns it to a property of a binding target; the target might be an HTML element, a component, or a directive. In the property binding, a template expression appears in quotes to the right of the = symbol as in [property]="expression". In interpolation syntax, the template expression is surrounded by double curly braces. For example, in the below interpolation, the template expression is {{username}},
<h3>{{username}}, welcome to Angular</h3>
The below javascript expressions are prohibited in template expression
- assignments (=, +=, -=, ...)
- new
- chaining expressions with ; or ,
- increment and decrement operators (++ and --)
A template statement responds to an event raised by a binding target such as an element, component, or directive. The template statements appear in quotes to the right of the = symbol like (event)="statement". Let's take an example of button click event's statement
<button (click)="editProfile()">Edit Profile</button>
In the above expression, editProfile is a template statement. The below JavaScript syntax expressions are not allowed.
- new
- increment and decrement operators, ++ and --
- operator assignment, such as += and -=
- the bitwise operators | and &
- the template expression operators
A pipe takes in data as input and transforms it to a desired output. For example, let us take a pipe to transform a component's birthday property into a human-friendly date using date pipe.
import { Component } from '@angular/core';
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date }}</p>`
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18); // June 18, 1987
}
A pipe can accept any number of optional parameters to fine-tune its output. The parameterized pipe can be created by declaring the pipe name with a colon ( : ) and then the parameter value. If the pipe accepts multiple parameters, separate the values with colons. Let's take a birthday example with a particular format(dd/MM/yyyy):
import { Component } from '@angular/core';
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date:'dd/MM/yyyy'}}</p>` // 18/06/1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
Note: The parameter value can be any valid template expression, such as a string literal or a component property.
You can chain pipes together in potentially useful combinations as per the needs. Let's take a birthday property which uses date pipe(along with parameter) and uppercase pipes as below
import { Component } from '@angular/core';
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date:'fullDate' | uppercase}} </p>` // THURSDAY, JUNE 18, 1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
Apart from built-inn pipes, you can write your own custom pipe with the below key characteristics,
- A pipe is a class decorated with pipe metadata @Pipe decorator, which you import from the core Angular library
For example,
@Pipe({name: 'myCustomPipe'})
- The pipe class implements the PipeTransform interface's transform method that accepts an input value followed by optional parameters and returns the transformed value.
The structure of pipeTransform would be as below,
interface PipeTransform { transform(value: any, ...args: any[]): any }
- The @Pipe decorator allows you to define the pipe name that you'll use within template expressions. It must be a valid JavaScript identifier.
template: `{{someInputValue | myCustomPipe: someOtherValue}}`
Every application has at least one Angular module, the root module that you bootstrap to launch the application is called as bootstrapping module. It is commonly known as AppModule. The default structure of AppModule generated by AngularCLI would be as follows,
/* JavaScript imports */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
/* the AppModule class with the @NgModule decorator */
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.
Most of the Front-end applications communicate with backend services over HTTP protocol using either XMLHttpRequest interface or the fetch() API. Angular provides a simplified client HTTP API known as HttpClient which is based on top of XMLHttpRequest interface. This client is avaialble from @angular/common/http
package.
You can import in your root module as below,
import { HttpClientModule } from '@angular/common/http';
The major advantages of HttpClient can be listed as below,
- Contains testability features
- Provides typed request and response objects
- Intercept request and response
- Supports Observalbe APIs
- Supports streamlined error handling
RxJS is a library for composing asynchronous and callback-based code in a functional, reactive style using Observables. Many APIs such as HttpClient produce and consume RxJS Observables and also uses operators for processing observables. For example, you can import observables and operators for using HttpClient as below,
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
An Observable instance begins publishing values only when someone subscribes to it. So you need to subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications. Let's take an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console.
Creates an observable sequence of 5 integers, starting from 1
const source = range(1, 5);
// Create observer object
const myObserver = {
next: x => console.log('Observer got a next value: ' + x),
error: err => console.error('Observer got an error: ' + err),
complete: () => console.log('Observer got a complete notification'),
};
// Execute with the observer object and Prints out each item
source.subscribe(myObserver);
// => Observer got a next value: 1
// => Observer got a next value: 2
// => Observer got a next value: 3
// => Observer got a next value: 4
// => Observer got a next value: 5
// => Observer got a complete notification
An Observable is a unique Object similar to a Promise that can help manage async code. Observables are not part of the JavaScript language so we need to rely on a popular Observable library called RxJS. The observables are created using new keyword. Let see the simple example of observable,
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
setTimeout(() => {
observer.next('Hello from a Observable!');
}, 2000);
});
Observer is an interface for a consumer of push-based notifications delivered by an Observable. It has below structure,
interface Observer<T> {
closed?: boolean;
next: (value: T) => void;
error: (err: any) => void;
complete: () => void;
}
A handler that implements the Observer interface for receiving observable notifications will be passed as a parameter for observable as below,
myObservable.subscribe(myObserver);
Note: If you don't supply a handler for a notification type, the observer ignores notifications of that type.
Angular elements are Angular components packaged as custom elements(a web standard for defining new HTML elements in a framework-agnostic way). Angular Elements hosts an Angular component, providing a bridge between the data and logic defined in the component and standard DOM APIs, thus, providing a way to use Angular components in non-Angular environments
.
The routing application should add
<base href="/">
The Angular Router which represents a particular component view for a given URL is not part of Angular Core. It is available in library named @angular/router
to import required router components. For example, we import them in app module as below,
import { RouterModule, Routes } from '@angular/router';
The RouterOutlet is a directive from the router library and it acts as a placeholder that marks the spot in the template where the router should display the components for that outlet. Router outlet is used like a component,
<router-outlet></router-outlet>
<!-- Routed components go here -->
The RouterLink is a directive on the anchor tags give the router control over those elements. Since the navigation paths are fixed, you can assign string values to router-link directive as below,
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" >List of todos</a>
<a routerLink="/completed" >Completed todos</a>
</nav>
<router-outlet></router-outlet>
RouterLinkActive is a directive that toggles css classes for active RouterLink bindings based on the current RouterState. i.e, the Router will add CSS classes when this link is active and and remove when the link is inactive. For example, you can add them to RouterLinks as below
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" routerLinkActive="active">List of todos</a>
<a routerLink="/completed" routerLinkActive="active">Completed todos</a>
</nav>
<router-outlet></router-outlet>
RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data. You can access the current RouterState from anywhere in the application using the Router service
and the routerState
property.
@Component({templateUrl:'template.html'})
class MyComponent {
constructor(router: Router) {
const state: RouterState = router.routerState;
const root: ActivatedRoute = state.root;
const child = root.firstChild;
const id: Observable<string> = child.params.map(p => p.id);
//...
}
}
During each navigation, the Router emits navigation events through the Router.events property allowing you to track the lifecycle of the route. The sequence of router events is as below,
- NavigationStart,
- RouteConfigLoadStart,
- RouteConfigLoadEnd,
- RoutesRecognized,
- GuardsCheckStart,
- ChildActivationStart,
- ActivationStart,
- GuardsCheckEnd,
- ResolveStart,
- ResolveEnd,
- ActivationEnd
- ChildActivationEnd
- NavigationEnd,
- NavigationCancel,
- NavigationError
- Scroll
ActivatedRoute contains the information about a route associated with a component loaded in an outlet. It can also be used to traverse the router state tree. The ActivatedRoute will be injected as a router service to access the information. In the below example, you can access route path and parameters,
@Component({...})
class MyComponent {
constructor(route: ActivatedRoute) {
const id: Observable<string> = route.params.pipe(map(p => p.id));
const url: Observable<string> = route.url.pipe(map(segments => segments.join('')));
// route.data includes both `data` and `resolve`
const user = route.data.pipe(map(d => d.user));
}
}
If the URL doesn't match any predefined routes then it causes the router to throw an error and crash the app. In this case, you can use wildcard route. A wildcard route has a path consisting of two asterisks to match every URL. For example, you can define PageNotFoundComponent for wildcard route as below
{ path: '**', component: PageNotFoundComponent }
No, the Routing Module is a design choice. You can skip routing Module (for example, AppRoutingModule) when the configuration is simple and merge the routing configuration directly into the companion module (for example, AppModule). But it is recommended when the configuration is complex and includes specialized guard and resolver services.
The expression used in an ngIf directive is used to narrow type unions in the Angular template compiler similar to if expression in typescript. So *ngIf allows the typeScript compiler to infer that the data used in the binding expression will never be undefined.
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.contact.email}} </span>'
})
class MyComponent {
user?: User;
}
The dependencies section of package.json with in an angular application can be divided as follow,
- Angular packages: Angular core and optional modules; their package names begin @angular/.
- Support packages: Third-party libraries that must be present for Angular apps to run.
- Polyfill packages: Polyfills plug gaps in a browser's JavaScript implementation.
A Zone is an execution context that persists across async tasks. Angular relies on zone.js to run Angular's change detection processes when native JavaScript operations raise events
The commonly-needed services, pipes, and directives provided by @angular/common module. Apart from these HttpClientModule is available under @angular/common/http.
A class decorator is a decorator that appears immediately before a class definition, which declares the class to be of the given type, and provides metadata suitable to the type The following list of decorators comes under class decorators,
- @Component()
- @Directive()
- @Pipe()
- @Injectable()
- @NgModule()
The class field decorators are the statements declared immediately before a field in a class definition that defines the type of that field. Some of the examples are: @input and @output,
@Input() myProperty;
@Output() myEvent = new EventEmitter();
Declarable is a class type that you can add to the declarations list of an NgModule. The class types such as components, directives, and pipes comes can be declared in the module. The structure of declarations would be,
declarations: [
YourComponent,
YourPipe,
YourDirective
],
Below classes shouldn't be declared,
- A class that's already declared in another NgModule
- Ngmodule classes
- Service classes
- Helper classes
An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners.
import { Subject } from 'rxjs';
const subject = new Subject<number>();
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
subject.next(1);
subject.next(2);
A platform is the context in which an Angular application runs. The most common platform for Angular applications is a web browser, but it can also be an operating system for a mobile device, or a web server. The runtime-platform is provided by the @angular/platform-* packages and these packages allow applications that make use of @angular/core
and @angular/common
to execute in different environments.
i.e, Angular can be used as platform-independent framework in different environments, For example,
- While running in the browser, it uses
platform-browser
package. - When SSR(server-side rendering ) is used, it uses
platform-server
package for providing web server implementation.
Angular Material is a collection of Material Design components for Angular framework following the Material Design spec. You can apply Material Design very easily using Angular Material.
It supports the most recent two versions of all major browsers. The latest version of Angular material is 8.1.1
The :host
pseudo-class selector is used to target styles in the element that hosts the component. Since the host element is in a parent component's template, you can't reach the host element from inside the component by other means.
For example, you can create a border for parent element as below,
//Other styles for app.component.css
//...
:host {
display: block;
border: 1px solid black;
padding: 20px;
}