Skip to content

Instantly share code, notes, and snippets.

@thamsrang
Last active September 20, 2019 13:32
Show Gist options
  • Save thamsrang/a98296b49e496d8a62d17c67d7a7e04a to your computer and use it in GitHub Desktop.
Save thamsrang/a98296b49e496d8a62d17c67d7a7e04a to your computer and use it in GitHub Desktop.
Angular Cheat Sheet. #js #angular

Cheat Sheet

Release Notes

Security

Compilation

๐Ÿ”— READ MORE:

Full Tutorial

Event Capturing

Errors & Debugging

Blogs

Q & A

CheatSheet

NgModule

Package and Module

Types of Modules

ngDoBootstrap - Dynamically bootstrapping components

Angular Life Cycle

How Life Cycle runs in Nested Component

Parent Child Life Cycle

Life Cycle Hooks for Components & Directives

A component has a lifecycle managed by Angular. Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change, and destroys it before removing it from the DOM.
ngOnChanges, ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, ngOnDestroy.

A Directive has the same set of lifecycle hooks.

class MyComponent{
  constructor(){

  }
   @Input() prop : number;
  ngOnChanges(changes: SimpleChanges) { // Return: viod, Params:  @angular/core/SimpleChanges - The changed properties. 
    // changes.prop contains the old and the new value...
  }
  ngOnInit(){ // Return: viod, Params: no params.

  }
  ngDoCheck(){ // Return: viod, Params: no params.

  }
      ngAfterContentInit(){ // Return: viod, Params: no params.

      }
      ngAfterContentChecked(){ // Return: viod, Params: no params.

      }
      ngAfterViewInit(){ // Return: viod, Params: no params.

      }
      ngAfterViewChecked(){ // Return: viod, Params: no params.

      }
  ngOnDestroy(){ // Return: viod, Params: no params.

  }
}

When to use Lifecycle Hooks

constructor vs ngOnInit

constructor() to setup Dependency Injection and not much else. ngOnInit() is for all the initialization/declaration and avoid stuff to work in the constructor.
constructor() - A class constructor in Angular is mostly used to inject dependencies.
ngOnInit() - ngOnInit is purely there to give us a signal that Angular has finished initialising the component. It is to perform initialization logic even if this logic doesnโ€™t depend on DI, DOM or input bindings.
Be careful on the logic that you put in your constructor because may depend on that is not available yet. Data is not always immediately available in the constructor, so it should do no more than set the initial local variables to simple values. Divide all the initial logic between the three Init hooks. The ngOnInit is a good place for a component to fetch its initial data;

ngOnChanges vs ngDoCheck

as we said ngOnChanges is called when a value bound to an input has changed so you can run custom code when an input has changed. ngDoCheck to the other hand is called when change detection runs so you can implement your custom change detection action, but be careful on using it because will run all the time there is a change detection and user experience will suffer;

ngAfterContentInit vs ngAfterViewInit

use ngAfterContent when you want to use the power of Query like @ContentChildren ( Content projection is a way to import HTML content from outside the component and insert that content into the componentโ€™s template in a designated spot, also as known as transclusion). Instead use ngAfterViewInit for any initialization that needs the view be rendered like jQuery plugin or simple external DOM manipulations, this will avoid you use setTimeout in most of the other hooks;

ngAfterContentChecked vs ngAfterViewChecked

both hooks has to be used carefully and have a lightweight implementation because every time happen a change detection these hooks are going to be called;

ngOnChanges vs ngAfterViewChecked

there is mostly two type of components, the reusable one, and the unique one. The reusable one uses more ngOnChanges the unique could use also the power of ngAfterViewCheck. So it is important to understand when ngOnChanges fires and when ngAfterViewCheck fires.

ngOnDestroy

This method will be invoked just before Angular destroys the component. Use this hook to unsubscribe observables and detach event handlers to avoid memory leaks.

Component

OPTIONS

ViewEncapsulation

ViewEncapsulation defines template and style encapsulation options available for Component's Component.

  • ViewEncapsulation.Emulated : 0 - Default.Use shimmed CSS that emulates the native behavior.
  • ViewEncapsulation.Native : 1 - Use shadow roots. This works only if natively available on the platform.
  • ViewEncapsulation.None : 2 - Use global CSS without any encapsulation.
  • ViewEncapsulation.ShadowDom : 3 - Use Shadow DOM to encapsulate styles. ShadowDom: https://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html

changeDetection: ChangeDetectionStrategy.OnPush

Others

Sharing Data Between Angular Components- Component Communication

@ViewChildren, @ViewChild, @ContentChildren & @ContentChild

ng-template, ng-container & ngTemplateOutlet

Directives

Directives allow you to attach behavior to elements in the DOM.

Options

selector

  • element-name: Select by element name.
  • .class: Select by class name.
  • [attribute]: Select by attribute name.
  • [attribute=value]: Select by attribute name and value.
  • :not(sub_selector): Select only if the element does not match the sub_selector.
  • selector1, selector2: Select if either selector1 or selector2 matches.

๐Ÿ”—References:

There are 3 types of directives:

1. Components

A component directive requires a view along with its attached behaviour. The component directive adds DOM elements, that have a template.


2. Structural Directives

Modifies the DOM layout by adding and removing DOM elements. Rather than adding new DOM elements, these types of directives modify the existing DOM and do not have templates.

TemplateRef

  • TemplateRef represents an embedded template that can be used to instantiate embedded

ViewContainerRef

  • ViewContainerRef represents a container where one or more views can be attached.

*ngfor - trackBy: fnName

We can help Angular to track which items added or removed by providing a trackBy function.
The trackBy function takes the index and the current item as arguments and needs to return the unique identifier for this item.
If you change the input data collection, Angular can track which items have been added or removed according to the unique identifier and create or destroy only the things that changed.

๐Ÿ”—Reference


3. Attribute Directives

Modifies the appearance or behavior of an element.
Rather than adding new DOM elements, these types of directives modify the existing DOM and do not have templates.

ElementRef

An ElementRef is backed by a render-specific element. In the browser, this is usually a DOM element.

Renderer

Angular renders a template into DOM.
Use a custom renderer to bypass Angular's templating and make custom UI changes that can't be expressed declaratively.

@HostBinding - Property Bind

The @HostBinding decorator a directive can link an internal property to an input property on the host element. So if the internal property changed the input property on the host element would also change.

@HostListener - AddEventListener

This is a function decorator that accepts an event name as an argument. When that event gets fired on the host element it calls the associated function.
We cann't remove @HostListener, i.e. can't remove event listener.

๐Ÿ”—Reference:

Pipes

A pipe takes in data as input and transforms it to a desired output.

Angular In-built Pipes

AsyncPipe, CurrencyPipe, DatePipe, DecimalPipe, I18nPluralPipe, I18nSelectPipe, JsonPipe, KeyValuePipe, LowerCasePipe, PercentPipe, SlicePipe, TitleCasePipe, UpperCasePipe.

Pure Pipes vs Impure Pipes

Pure Pipe - Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).
Angular ignores changes within (composite) objects. It won't call a pure pipe if you change an input month, add to an input array, or update an input object property.
Pure Pipe produce the same output when invoked with the same set of arguments. Example: DatePipe, UpperCasePipe and LowerCasePipe

Impure Pipe - Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, as often as every keystroke or mouse-move.
With that concern in mind, implement an impure pipe with great care. An expensive, long-running pipe could destroy the user experience. Example: JsonPipe and SlicePipe

Stateful Pipes vs Stateless Pipes

  • Stateless pipes are pure functions that flow input data through without remembering anything or causing detectable side-effects. Most pipes are stateless.

  • Stateful pipes are those which can manage the state of the data they transform. A pipe that creates an HTTP request, stores the response and displays the output, is a stateful pipe. Stateful Pipes should be used cautiously.

Chaining pipes

We can chain pipes together to make use of multiple pipes in one expression.

Routing & Navigation

Routes

  • Routes

    Different Phases of Router

    Angular router performs the following 7 steps. In short PRIGRAM
    1. Parse: It parses the browser URL the user wants to navigate to
    2. Redirect: It applies a URL redirect (if one is defined)
    3. Identify: It identifies which router state corresponds to the URL
    4. Guard: It runs the guards that are defined in the router state
    5. Resolve: It resolves the required data for the router state
    6. Activate: It activates the Angular components to display the page
    7. Manage: It manages navigation and repeats the process when a new URL is requested

RouterEvent

Router Events

CanLoad

CanLoad

CanActivate - Guard

CanActivate

canActivate vs canLoad

  • canActivate is used to prevent an unauthorized user

  • canLoad is used to prevent the entire module of app

  • canActivate - Code is downloaded.

  • canLoad - Code will not get downloaded. canLoad used for LazyLoaded Modules.

The CanLoad guard blocks loading of feature module assets until authorized to do so. If you want to both preload a module and guard against unauthorized access, use the CanActivate guard instead.

CanActivateChild

CanActivateChild

CanDeactivate

CanDeactivate

Resolve

Resolve

๐Ÿ”— Reference

Router Outlet

RouterOutlet

๐Ÿ”— References

Router

Router

Routerstate

Routerstate

RouteStateSnapshot

ActivatedRoute

ActivatedRoute

ActivatedRouteSnapshot

๐Ÿ”— Reference

routerLink, queryParams & fragment

Eager Loading, Lazy Loading and Preloading

UrlSerializer - URL Parser

Routing Strategies

PathLocationStrategy

  • The default client side routing strategy used in Angular is the PathLocationStrategy.
  • It takes advantage of a relatively new HTML5 API called pushstate (from the HTML5 history API).
  • By using pushstate we can change the URL and not have the browser request the page from the server and without needing to use a hash fragment.
  • base href - When using the PathLocationStrategy we need to tell the browser what will be prefixed to the requested path to generate the URL.
<base href='/my/app'/>
  • Either base href OR you can provide it to the DI framework it via the symbol APP_BASE_HREF.
import {Component, NgModule} from '@angular/core';
import {APP_BASE_HREF} from '@angular/common';

@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
})
class AppModule {}

HashLocationStrategy

  • To enable HashLocationStrategy in an Angular application we pass {useHash: true} when we are providing our routes with RouterModule.
  RouterModule.forRoot(routes, {useHash: true})
  • The # part of the url is called the hash fragment.
  • TO provide link to a particular section in a HTML page.
<a name="routing-strategies"></a>

Share data through Router

  • Pass data using route - data attribute
  • Pass data using Query Parameters - Using NavigationExtras
  • Pass data using Application Providers - Using Services @Injectable()

๐Ÿ”— Reference

onSameUrlNavigation: 'reload' | 'ignore'

runGuardsAndResolvers: "always"

RouteReuseStrategy

Http Client Module

HttpClient

HttpClient is available as an injectable class, with methods to perform HTTP requests.

HTTPClient Methods: request(), delete(), get(), head(), jsonp(), options(), patch(), post(), put()

HttpParams

HttpHeaders

JsonpModule, HttpClientJsonpModule


HttpInterceptor

{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }  

https://medium.com/@MetonymyQT/angular-http-interceptors-what-are-they-and-how-to-use-them-52e060321088

HttpRequest

HttpEventType

HttpEvent

type HttpEvent<T> = HttpSentEvent | HttpHeaderResponse | HttpResponse<T> | HttpProgressEvent | HttpUserEvent<T>;

HttpHandler

HttpResponse

HTTP vs HTTPClient

ErrorHandler

Provides a hook for centralized exception handling.
The default implementation of ErrorHandler prints error messages to the console.

Custom ErrorHandler

import { Injectable, ErrorHandler, Injector } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { Router } from '@angular/router';

@Injectable()
export class GlobalErrorHandlerService implements ErrorHandler {
    constructor(private injector: Injector) { }    

    handleError(error: any) {
      let router = this.injector.get(Router);
      console.log('URL: ' + router.url);
      
     // Authentication Error
     // https://medium.com/@amcdnl/authentication-in-angular-jwt-c1067495c5e0
      
      if (error instanceof HttpErrorResponse) {
          //Backend returns unsuccessful response codes such as 404, 500 etc.				  
          console.error('Backend returned status code: ', error.status);
          console.error('Response body:', error.message);          	  
      } else {
          //A client-side or network error occurred.	          
          console.error('An error occurred:', error.message);          
      }     
      router.navigate(['/error']);
    }
}

๐Ÿ”— Reference

FORMS

Angular FORM supports two-way data binding, change tracking, validation, and error handling. Using this we can lay out the controls creatively, bind them to data, specify validation rules and display validation errors, conditionally enable or disable specific controls, trigger built-in visual feedback, and much more.

Attributes

novalidate

novalidate attribute is used to disable browser's native form validation.

<form action="/action_page.php" novalidate>
  E-mail: <input type="email" name="user_email">
  <input type="submit">
</form>

ngNativeValidate

If you want to use native validation with Angular forms, just add ngNativeValidate.

ngNoForm

When you add ngNoForm, you turn off Angular's form registration helpers. In other words, the NgForm directive is never activated. This is the directive that knows how to interact with custom value accessors. Without it, you're just using HTML5 forms at the top level, which of course won't know anything about your custom input. This is expected behavior for ngNoForm, so I'm going to close this. ๐Ÿ”—Reference.

Template Driven FORM

In the template-driven approach the form structure and logic is mainly implemented in HTML. Based on this a representation of the form in TypeScript is generated automatically.

  • The structure and logic of a form is fix.
  • The number of form fields does not vary
  • Form validation rules are the same for different user roles.

ngForm

ngSubmit

ngModelGroup

ngModel

ngModel Validation CSS Classes

  • ng-touched: Control has been visited
  • ng-untouched: Control has not been visited
  • ng-dirty: Control's value has been changed
  • ng-pristine: Control's value hasn't been changed
  • ng-valid: Control's value is valid. Valid for maxLength, minLength, pattern and required.
  • ng-invalid: Control's value isn't valid

๐Ÿ”— Examples:

  • Login forms, Reset password forms, Forms to enter and edit Address data, Order data and similar fix data structures.

๐Ÿ”— References:

Reactive FORM

  • Handling a event based on a debounce time.
  • Handling events when the components are distinct until changed.
  • Adding elements dynamically.
  • Results in a better testable form by leveraging a decoupling between the HTML (design/CSS team can work here) and component's business rules.
  • To improve the user experience with features like reactive transformations, correlated validations and handle complex scenarios as runtime validation rules.

ReactiveFormsModule

FormControl

An individual form input, checkbox, select, textarea, etc.

FormGroup

A group of form fields that can be manipulated and validated together.

FormBuilder

A service that helps you build FormGroups easily.

Validators

[formGroup]

[formGroupName]

[formControlName]

FormControls

FormArray

Custom Validator

๐Ÿ”— Reference

ControlValueAccessor

A ControlValueAccessor acts as a bridge between the Angular forms API and a native element in the DOM. ๐Ÿ”— Example

๐Ÿ”— Example

๐Ÿ”— Reference

Reactive FORM vs Template Driven FORM

๐Ÿ”— Reference

Dependency Injection & Providers

The DI framework in Angular consists of 4 concepts working together:

Token

  • This uniquely identifies something that we want injected. A dependancy of our code.

Dependancy

  • The actual code we want injected.

๐Ÿ”— Reference


Provider

  • Provider is a map between a token and a list of dependancies.
  • Describes how the Injector should be configured.
  • NgModule.providers vs Component.providers vs Component.viewProviders

Injector, ReflectiveInjector, StaticInjector

@Inject decorator

  • @Inject() is a manual mechanism for letting Angular know that a parameter must be injected.
  • When using TypeScript, @Inject is only needed for injecting primitives.
  import { Component, Inject } from '@angular/core';
  import { ChatWidget } from '../components/chat-widget';

  @Component({
    selector: 'app-root',
    template: `Encryption: {{ encryption }}`
  })
  export class AppComponent {
    encryption = this.chatWidget.chatSocket.encryption;

    constructor(@Inject(ChatWidget) private chatWidget) { }
  }

@Injectable decorator

  • @Injectable() lets Angular know that a class can be used with the dependency injector.
  • @Injectable() is not strictly required if the class has other Angular decorators on it or does not have any dependencies.

๐Ÿ”— Reference

NgZone

NgZone is basically a forked zone that extends its API and adds some additional functionality to its execution context. One of the things it adds to the API is the following set of custom events we can subscribe to, as they are observable streams:

NgZone.onTurnStart() ==> NgZone.onUnstable() - Notifies subscribers just before Angularโ€™s event turn starts. Emits an event once per browser task that is handled by Angular.

NgZone.onTurnDone() ==> NgZone.onMicrotaskEmpty() - Notifies subscribers immediately after Angularโ€™s zone is done processing the current turn and any micro tasks scheduled from that turn.

NgZone.onEventDone() => NgZone.onStable() - Notifies subscribers immediately after the final onTurnDone() callback before ending VM event. Useful for testing to validate application state.

zone.js

Zones is a new mechanism that helps developers work with multiple logically-connected async operations. Zones work by associating each async operation with a zone.
Without zones, we donโ€™t get any change detection, so we donโ€™t get any of the nice UI updates that weโ€™d expect!
A developer can take advantage of this binding to:

  • Associate some data with the zone, analogous to thread-local storage in other languages, which is accessible to any async operation inside the zone.
  • Automatically track outstanding async operations within a given zone to perform cleanup or rendering or test assertion steps
  • Time the total time spent in a zone, for analytics or in-the-field profiling
  • Handle all uncaught exceptions or unhandled promise rejections within a zone, instead of letting them propagate to the top level

๐Ÿ”— Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment