Angular CDK

 Angular Component Development Kit was released in July 2017. It is a package of components which is used to build most Angular Material tools. A drawback of Angular Materials library is that it is not easily customizable. The Google team decoupled a set of low level components from the Material code, that is the CDk package. Therefore It is similar to the Material kit. Angular CDK has 7 common behaviors and 2 components. Two of the core concepts of Angular Material library are Portal and PortalHost. Portal is a part of the UI which you want to apply anywhere else. It could be a Component or TemplateRef. PortalHost is the place you render the Portal. When you build your project the first thing you do is to create a component. We will use an example to easily understand CDK.


import {

  Injectable,

  ComponentFactoryResolver,

  ApplicationRef,

  Injector

} from '@angular/core';

import {

  ComponentType,

  Portal,

  ComponentPortal,

  DomPortalHost

} from '@angular/cdk';


@Injectable()

export class LoadingSpinnerService {


  // 1. Reference to our Portal.

  //    This is the portal we'll use to attach our LoadingSpinnerComponent.

  private loadingSpinnerPortal: ComponentPortal<LoadingSpinnerComponent>;


  // 2. Reference to our Portal Host.

  //    We use DOMPortalHost as we'll be using document.body as our anchor.

  private bodyPortalHost: DomPortalHost;


  // 3. Inject the dependencies needed by the DOMPortalHost constructor

  constructor(

    private componentFactoryResolver: ComponentFactoryResolver,

    private appRef: ApplicationRef,

    private injector: Injector) {


      // 4. Create a Portal based on the LoadingSpinnerComponent

      this.loadingSpinnerPortal = new ComponentPortal(LoadingSpinnerComponent);


      // 5. Create a PortalHost with document.body as its anchor element

      this.bodyPortalHost = new DomPortalHost(

        document.body,

        this.componentFactoryResolver,

        this.appRef,

        this.injector);

  }


  reveal() {

    // 6. Attach the Portal to the PortalHost.

    this.bodyPortalHost.attach(this.loadingSpinnerPortal);

  }


  hide() {

    // 7. Detach the Portal from the PortalHost

    this.bodyPortalHost.detach();

  }

}


What we did in this example is we created a reference to the Portal. Then created a reference to the PortalHost using document.body to inject our component. Injected dependencies. To build PortalHost these dependencies are needed by DomPortalHost. Creates a Portal and PortalHost.shows the component by attaching it to PortalHost then hides the spinner. Hide component by removing it from the PortalHost.