Angular component page lifecycle are :
<li>Name: {{ user.name }}</li> <li>Address: {{ user.address }}</li>
<input type="email" [value]="user.email">
<button (click)="logout()"></button>
<input type="email" [(ngModel)]="user.email">
Class decorators, e.g. @Component and @NgModule
import { NgModule, Component } from '@angular/core'; @Component({ selector: 'my-component', template: ' Class decorator', }) export class MyComponent { constructor() { console.log('My Component'); } } @NgModule({ imports: [], declarations: [], }) export class MyModule { constructor() { console.log('My Module!'); } }
Property decorators Used for properties inside classes, e.g. @Input and @Output
import { Component, Input } from '@angular/core'; @Component({ selector: 'my-component', template: ' Property decorator' }) 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: ' Method decorator' }) export class MyComponent { @HostListener('click', ['$event']) onHostClick(event: Event) { // clicked, `event` available } }
Parameter decorators Used for parameters inside class constructors, e.g. @Inject
import { Component, Inject } from '@angular/core'; import { MyService } from './my-service'; @Component({ selector: 'my-component', template: ' Parameter decorator' }) export class MyComponent { constructor(@Inject(MyService) myService) { console.log(myService); // MyService } }
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 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: ` ` }) export class AsyncObservablePipeComponent { time = new Observable(observer => setInterval(() => observer.next(new Date().toString()), 2000) ); }observable|async
: Time: {{ time | async }}
We use Angular ngFor directive in the template to display each item in the list. For example, here we iterate over list of users,
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,
18">You are not eligible for student pass!
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 Syntax'; }
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,
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}},
{{username}}, welcome to Angular
The below javascript expressions are prohibited in template expression
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: ` Birthday is {{ birthday | date }}
` }) 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):
mport { Component } from '@angular/core'; @Component({ selector: 'app-birthday', template: ` Birthday is {{ birthday | date:'dd/mm/yyyy'}}
` // 18/06/1987 }) export class BirthdayComponent { birthday = new Date(1987, 6, 18); }
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: ` Birthday is {{ birthday | date:'fullDate' | uppercase}}
` // 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,
1. A pipe is a class decorated with pipe metadata @Pipe decorator, which you import from the core Angular library For example
@Pipe({name: 'myCustomPipe'})
2. 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 }
3. 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}}`
You can create custom reusable pipes for the transformation of existing value. For example, let us create a custom pipe for finding file size based on an extension,
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'customFileSizePipe'}) export class FileSizePipe implements PipeTransform { transform(size: number, extension: string = 'MB'): string { return (size / (1024 * 1024)).toFixed(2) + extension; } }
Now you can use the above pipe in template expression as below,
template: ` Find the size of a file
Size: {{288966 | customFileSizePipe: 'GB'}}
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,
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 { }
The response body doesn't may not return full response data because sometimes servers also return special headers or status code which which are important for the application workflow. Inorder to get full response, you should use observe option from HttpClient,
getCustomerResponse(): Observable > { return this.http.get ( this.userUrl, { observe: 'response' }); }
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 myObservable.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 { 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);
Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution. Let's demonstrate the multi-casting feature,
var source = Rx.Observable.from([1, 2, 3]); var subject = new Rx.Subject(); var multicasted = source.multicast(subject); // These are, under the hood, `subject.subscribe({...})`: multicasted.subscribe({ next: (v) => console.log('observerA: ' + v) }); multicasted.subscribe({ next: (v) => console.log('observerB: ' + v) }); // This is, under the hood, `s
You can handle errors by specifying an error callback on the observer instead of relying on try/catch which are ineffective in asynchronous environment. For example, you can define error callback as below,
myObservable.subscribe({ next(num) { console.log('Next num: ' + num)}, error(err) { console.log('Received an errror: ' + err)} });
The subscribe() method can accept callback function definitions in line, for next, error, and complete handlers is known as short hand notation or Subscribe method with positional arguments. For example, you can define subscribe method as below,
myObservable.subscribe( x => console.log('Observer got a next value: ' + x), err => console.error('Observer got an error: ' + err), () => console.log('Observer got a complete notification') );
RxJS provides creation functions for the process of creating observables from things such as promises, events, timers and Ajax requests. Let us explain each of them with an example,
1. Create an observable from a promise
import { from } from 'rxjs'; // from function const data = from(fetch('/api/endpoint')); //Created from Promise data.subscribe({ next(response) { console.log(response); }, error(err) { console.error('Error: ' + err); }, complete() { console.log('Completed'); } });
Create an observable that creates an AJAX request
import { ajax } from 'rxjs/ajax'; // ajax function const apiData = ajax('/api/data'); // Created from AJAX request // Subscribe to create the request apiData.subscribe(res => console.log(res.status, res.response));
Create an observable from a counter
import { interval } from 'rxjs'; // interval function const secondsCounter = interval(1000); // Created from Counter value secondsCounter.subscribe(n => console.log(`Counter value: ${n}`));
Create an observable from an event
import { fromEvent } from 'rxjs'; const el = document.getElementById('custom-element'); const mouseMoves = fromEvent(el, 'mousemove'); const subscription = mouseMoves.subscribe((e: MouseEvent) => { console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`); });
You can use the NgElement
and WithProperties
types exported from @angular/elements.
Let's see how it can be applied by comparing with Angular component, The simple container with input property would be as below,
@Component(...) class MyContainer { @Input() message: string; }
After applying types typescript validates input value and their types,
const container = document.createElement('my-container') as NgElement & WithProperties<{message: string}> ; container.message = 'Welcome to Angular elements!'; container.message = true; // <-- ERROR: TypeScript knows this should be a string. container.greet='News' ; // <-- ERROR: TypeScript knows there is no `greet` property on `container`.