Angular
Angular
Angular is a TypeScript-based front-end web application framework. It targets both the browser and the server.
Angular is one of the most popular frameworks for UI design today, with thousands of developers worldwide contributing to its community project.
Its compelling features and performance have made it an essential tool for any web developer to have in their toolbox.
It is maintained by Google, and its primary function is to design single-page applications.
Angular has significant advantages as a framework, while also providing a common architecture for developers to work with.
It allows developers to create large, maintainable applications.
Setup
To install and work on angular we require following tools:
Node.js download from this link node.js.
Node.js is open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside a browser. It is free to use and run-on various platforms (Windows, Linux, UNIX, Mac, etc.) The NPM program is installed in our computer when we install node.js. it hosts millions of free packages to download and use.
IDE (visual studio) for writing our code. download vscode editor from this link Visual Studio.
Start New Project
To work on angular first run following command in node.js to get angular CLI for managing project.
npm install -g @angular/cli
Create a new project with following command:
ng new my-app
Angular will prompt you to configure the project. For the default settings, you can press the Enter or Return keys.
Run a project with command:
ng serve -open
or
ng s -o
After that, the default local host has been automatically created and opens in our system from Local host 4200.
Create new component/route/service using following command:
ng generate
or
ng g
Next, we can add and edit our code in VS Code to do our project, and all our libraries and files are there to the system.
build for deployment in dist folder
ng build
or
ng b
Test spec files
ng test
end-to-end tests
ng e2e
or
ng e
run linting
ng lint
or
ng l
Identify dependencies to update
ng update
Add libraries like material
ng add
Lifecycle Hooks
Components emit events during and after initialization. Angular allows us to hook into these events by defining a set of methods in a component's class.
ngOnChanges : run after an input/output binding has been changed.
ngOnInit : run after a component has been initialized. Input bindings are ready.
ngDoCheck : Allows developers to perform custom actions during change detection.
ngAfterContentInit : Runs after the content of a component has been initialized.
ngAfterContentChecked : Runs after every check of a component's content.
ngAfterViewInit : Runs after the view of a component has been initialized.
ngAfterViewChecked : Runs after every check of a component's view.
ngOnDestroy : Runs before a component is destroyed.
Services
Services are objects for outsourcing logic and data that can be injected into our components. They're handy for reusing code in multiple components. they can serve as an alternative to state management libraries. We can create services with commands:
ng generate service MyService
or
ng g s MyService
Services are not standalone. Most commonly they are injected in app components. There are two steps for injecting a service. First, we must add the @Injectable () decorator.
import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
constructor() { }
}
Secondly, we need to inject this class in angular. There are three options at our disposal.
1. Injectable Decorator
It allows the service to be injectable anywhere in our app.
@Injectable({
providedIn: 'root'
})
2. Module
It allows a service to be injectable in classes that are imported in the same module.
@NgModule({
declarations: [],
imports: [],
providers: [MyService}],
bootstrap: []
})
3. Component Class
It allows a service to be injectable in a single component class.
@Component({
providers: [MyService]
})
Once you've got those two steps settled, a service can be injected into the constructor()
function of a class:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: '<p>Hello World</p>',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
constructor(private myService: MyService) { }
}
Modules
Classes decorated with the @NgModule() decorator can register components, services, directives, and pipes.
Following options can be added to a module:
declarations - List of components, directives, and pipes that belong to this module.
imports - List of modules to import into this module. Everything from the imported modules is available to declarations of this module.
exports - List of components, directives, and pipes visible to modules that import this module.
providers - List of dependency injection providers visible both to the contents of this module and to importers of this module.
bootstrap - List of components to bootstrap when this module is bootstrapped.
Here's an example of a module called AppModule.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Angular Directives
There are two types of directives: attribute directives and structural directives.
Attribute Directives
It deals with changing the look and behavior of the DOM element. It changes the behavior of an element, component, or another directive. Angular exports the following attribute directives:
NgClass
Adds and removes a set of CSS classes.
<!-- toggle the "special" class on/off with a property -->
<div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>
NgStyle
Adds and removes a set of HTML styles.
<div [ngStyle]="{
'font-weight': 2 + 2 === 4 ? 'bold' : 'normal',
}">
This div is initially bold.
</div>
NgModel
Adds two-way data binding to an HTML form element. Firstly, this directive requires the
FormsModule to be added to the @NgModule() directive.
import { FormsModule } from '@angular/forms'; // <--- JavaScript import from Angular
/* . . . */
@NgModule({
/* . . . */
imports: [
BrowserModule,
FormsModule // <--- import into the NgModule
],
/* . . . */
})
export class AppModule { }
Secondly, we can bind the [(ngModel)] directive on an HTML <form> element and set it
equal to the property.
<label for="example-ngModel">[(ngModel)]:</label>
<input [(ngModel)]="currentItem.name" id="example-ngModel">
The `NgModel` directive has more customizable options that can be at this link
(https://angular.io/guide/built-in-directives#displaying-and-updating-properties-withngmodel).
Structural Directives
Structural Directives are used to manipulate and change the structure of the DOM elements. Structural directives have a star (*) sign before the directive. Like as, *ngIf, *ngFor, and *ngSwitch directive.
NgIf
A directive that will conditionally create or remove elements from the template. If the
value of the NgIf directive evaluates to false, Angular removes the element.
<p *ngIf="isActive">Hello World!</p>
NgFor
Loops through an element in a list/array.
<div *ngFor="let item of items">{{item.name}}</div>
NgSwitch
An alternative directive for conditionally rendering elements. This directive acts very similarly, to the JavaScript switch statement. There are three directives at our disposal:
NgSwitch — A structural directive that should be assigned the value that should be
matched against a series of conditions.
NgSwitchCase — A structural directive that stores a possible value that will be
matched against the NgSwitch directive.
NgSwitchDefault — A structural directive that executes when the expression doesn't
match with any defined values.
<ul [ngSwitch]="food">
<li *ngSwitchCase="’Salad’">Salad</li>
<li *ngSwitchCase="’Sweet’">Pizza</li>
<li *ngSwitchCase="’Curry’">Curry</li>
<li *ngSwitchDefault>Corn</li>
</ul>
Custom Directives
We're not limited to directives defined by Angular. We can create custom directives with the following command:
# Common
ng generate directive MyDirective
# Shorthand
ng g d MyDirective
To identify directives, classes are decorated with the @Directive() decorator. Here's what a common directive would look like:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appMyDirective]'
})
export class appMyDirective {
constructor(private elRef: ElementRef) {
eleRef.nativeElement.style.background = 'red';
}
}
Pipes
Pipes are known for transforming content but not directly affecting data. They're mainly utilized in templates like so:
{{ 'Hello world' | uppercase }}
Angular has a few pipes built-in.
DatePipe
Formats a date value according to locale rules.
{{ value_expression | date 'short' }}
UpperCasePipe
Transforms text to all upper case.
{{ 'Hello world' | uppercase }}
LowerCasePipe
Transforms text to all lower case.
{{ 'Hello World' | lowercase }}
CurrencyPipe
Transforms a number to a currency string, formatted according to locale rules.
{{ 1.3495 | currency:'CAD' }}
DecimalPipe
Transforms a number into a string with a decimal point, formatted according to locale
rules.
{{ 3.14159265359 | number }}
PercentPipe
Transforms a number to a percentage string, formatted according to locale rules. -
{{ 0.259 | percent }}
Decorators
Angular exports number of decorators that can be applied to classes and fields. These are some of the most common decorators you'll come across.
@Input() A property can be updated through property binding e.g., @Input() myProperty
@Output() A property that can fire events and can be subscribed to with event binding on a component. e.g., @Output() myEvent = new EventEmitter();
@HostBinding() Binds a host element property (here, the CSS class valid) to a directive/component property (isValid). e.g., @HostBinding('class.valid') isValid
@HostListener() directive for subscribing to an event on a host element, such as a click event, and run a method when that event is emitted. You can optionally accept the $event object. @HostListener('click', ['$event']) onClick(e) {...}
@ContentChild() Binds the first result of the component content query ( myPredicate ) to a property ( myChildComponent ) of the class. ContentChild(myPredicate) myChildComponent;
@ContentChildren() Binds the results of the component content query ( myPredicate ) to a property ( myChildComponents ) of the class. @ContentChildren(myPredicate) myChildComponents;
@ViewChild() Binds the first result of the component view query ( myPredicate ) to a property ( myChildComponent ) of the class. Not available for directives. @ViewChild(myPredicate) myChildComponent;
@ViewChildren() Binds the results of the component view query ( myPredicate ) to a property ( myChildComponents ) of the class. Not available for directives. @ViewChildren(myPredicate) myChildComponents;