Angular CDK Common Behaviors

Go back to Tutorial

Material components are using the CDK extensively as most of behaviours are now moved (or being moved) to the CDK, and the components are left to deal with only the UI. There are 2 key benefits to this:

  • Separation of concerns: You can now develop your features using Material CDK without being bothered by UI constraints along the way.
  • Low-imprint UI library: You will not have to apply the Material UI components anymore to use the features provided. This means no more endless CSS overriding!

CDK features are not all documented yet, but most of them are well commented and pretty easy to use.

Accessibility

The a11y package provides a number of tools to improve accessibility, described below.

  • ListKeyManager – ListKeyManager manages the active option in a list of items based on keyboard interaction. Intended to be used with components that correspond to a role=”menu” or role=”listbox” pattern.
  • FocusTrap – The cdkTrapFocus directive traps Tab key focus within an element. This is intended to be used to create accessible experience for components like modal dialogs, where focus must be constrained.
  • InteractivityChecker – InteractivityChecker is used to check the interactivity of an element, capturing disabled, visible, tabbable, and focusable states for accessibility purposes.
  • LiveAnnouncer – LiveAnnouncer is used to announce messages for screen-reader users using an aria-live region.
  • FocusMonitor – The FocusMonitor is an injectable service that can be used to listen for changes in the focus state of an element. It’s more powerful than just listening for focus or blur events because it tells you how the element was focused (via mouse, keyboard, touch, or programmatically). It also allows listening for focus on descendant elements if desired. To listen for focus changes on an element, use the monitor method which takes an element to monitor and an optional boolean flag checkChildren. Passing true for checkChildren will tell the FocusMonitor to consider the element focused if any of its descendants are focused. This option defaults to false if not specified. The monitor method will return an Observable that emits the FocusOrigin whenever the focus state changes.

Bidirectionality

The bidi package provides a common system for components to get and respond to change in the application’s LTR/RTL layout direction.

  • Directionality – When including the CDK’s BidiModule, components can inject Directionality to get the current text direction (RTL or LTR);
  • The Dir directive – The BidiModule also includes a directive that matches any elements with a dir attribute. This directive has the same API as Directionality and provides itself _as_ Directionality. By doing this, any component that injects Directionality will get the closest ancestor layout direction context.

Drag and Drop

The @angular/cdk/drag-drop module provides you with a way to easily and declaratively create drag-and-drop interfaces, with support for free dragging, sorting within a list, transferring items between lists, animations, touch devices, custom drag handles, previews, and placeholders, in addition to horizontal lists and locking along an axis.

Start by importing DragDropModule into the NgModule where you want to use drag-and-drop features. You can now add the cdkDrag directive to elements to make them draggable. When outside of a cdkDropList element, draggable elements can be freely moved around the page. You can add cdkDropList elements to constrain where elements may be dropped.

Adding cdkDropList around a set of cdkDrag elements groups the draggables into a reorderable collection. Items will automatically rearrange as an element moves. Note that this will not update your data model; you can listen to the cdkDropListDropped event to update the data model once the user finishes dragging.

The cdkDropList directive supports transferring dragged items between connected drop zones. You can connect one or more cdkDropList instances together by setting the cdkDropListConnectedTo property or by wrapping the elements in an element with the cdkDropListGroup attribute.

You can associate some arbitrary data with both cdkDrag and cdkDropList by setting cdkDragData or cdkDropListData, respectively. Events fired from both directives include this data, allowing you to easily identify the origin of the drag or drop interaction.

Layout

The layout package provides utilities to build responsive UIs that react to screen-size changes.

  • BreakpointObserver – BreakpointObserver is a utility for evaluating media queries and reacting to their changing.
  • MediaMatcher – MediaMatcher is a lower-level utility that wraps the native matchMedia. This service normalizes browser differences and serves as a convenient API that can be replaced with a fake in unit tests. The matchMedia method can be used to get a native MediaQueryList.

Observers

The observers package provides convenience directives built on top of native web platform observers, such as MutationObserver.

cdkObserveContent – A directive for observing when the content of the host element changes. An event is emitted when a mutation to the content is observed.

<div class=”projected-content-wrapper” (cdkObserveContent)=”projectContentChanged()”>

<ng-content></ng-content>

</div>

Overlay

The overlay package provides a way to open floating panels on the screen.

Initial setup – The CDK overlays depend on a small set of structural styles to work correctly. If you’re using Angular Material, these styles have been included together with the theme, otherwise if you’re using the CDK on its own, you’ll have to include the styles yourself. You can do so by importing the prebuilt styles in your global stylesheet:

@import ‘~@angular/cdk/overlay-prebuilt.css’;

Creating overlays – Calling overlay.create() will return an OverlayRef instance. This instance is a handle for managing that specific overlay.

The OverlayRef _is_ a PortalOutlet- once created, content can be added by attaching a Portal.

Configuring an overlay – When creating an overlay, an optional configuration object can be provided.

const overlayRef = overlay.create({

height: ‘400px’,

width: ‘600px’,

});

The full set of configuration options can be found in the API documentation.

Position Strategies – The positionStrategy configuration option determines how the overlay will be positioned on-screen. There are two position strategies available as part of the library: GlobalPositionStrategy and ConnectedPositionStrategy.

  • GlobalPositionStrategy is used for overlays that require a specific position in the viewport, unrelated to other elements. This is commonly used for modal dialogs and application-level notifications.
  • ConnectedPositionStrategy is used for overlays that are positioned relative to some other “origin” element on the page. This is commonly used for menus, pickers, and tooltips. When using the connected strategy, a set of preferred positions is provided; the “best” position will be selected based on how well the overlay would fit within the viewport.

Scroll Strategies – The scrollStrategy configuration option determines how the overlay will react to scrolling outside the overlay element. There are four scroll strategies available as part of the library.

  • NoopScrollStrategy is the default option. This strategy does nothing.
  • CloseScrollStrategy will automatically close the overlay when scrolling occurs.
  • BlockScrollStrategy will block page scrolling while the overlay is open. Note that some applications may implement special or customized page scrolling; if the BlockScrollStrategy conflicts with this kind of situation, it can be overriden by re-providing BlockScrollStrategy with a custom implementation.
  • RepositionScrollStrategy will re-position the overlay element on scroll. Note that this will have some performance impact on scrolling- users should weigh this cost in the context of each specific application.

The overlay container – The OverlayContainer provides a handle to the container element in which all individual overlay elements are rendered. By default, the overlay container is appended directly to the document body so that an overlay is never clipped by an overflow: hidden parent.

Platform

A set of utilities that gather information about the current platform and the different features it supports.

Platform information:

  • Is Android: false
  • Is iOS: false
  • Is Firefox: true
  • Is Blink: false
  • Is Webkit: false
  • Is Trident: false
  • Is Edge: false
  • Supported input types: color, button, checkbox, date, email, file, hidden, image, number, password, radio, range, reset, search, submit, tel, text, time, url
  • Supports passive event listeners: true
  • Supports scroll behavior: true

Portal

The portals package provides a flexible system for rendering dynamic content into an application. A Portal is a piece of UI that can be dynamically rendered to an open slot on the page. The “piece of UI” can be either a Component or a TemplateRef and the “open slot” is a PortalOutlet. Portals and PortalOutlets are low-level building blocks that other concepts, such as overlays, are built upon.

Portal<T>

Method Description
attach(PortalOutlet): T Attaches the portal to a host.
detach(): void Detaches the portal from its host.
isAttached: boolean Whether the portal is attached.

PortalOutlet

Method Description
attach(Portal): any Attaches a portal to the host.
detach(): any Detaches the portal from the host.
dispose(): void Permanently dispose the host.
hasAttached: boolean Whether a portal is attached to the host.
  • CdkPortal – Used to get a portal from an <ng-template>. CdkPortal is a Portal.
  • ComponentPortal – Used to create a portal from a component type. When a component is dynamically created using portals, it must be included in the entryComponents of its NgModule.
  • CdkPortalOutlet – Used to add a portal outlet to a template. CdkPortalOutlet is a PortalOutlet.

Scrolling

The scrolling package provides helpers for directives that react to scroll events.

cdkScrollable and ScrollDispatcher – The cdkScrollable directive and the ScrollDispatcher service together allow components to react to scrolling in any of its ancestor scrolling containers.

The cdkScrollable directive should be applied to any element that acts as a scrolling container. This marks the element as a Scrollable and registers it with the ScrollDispatcher. The dispatcher, then, allows components to share both event listeners and knowledge of all of the scrollable containers in the application.

ViewportRuler – The ViewportRuler is a service that can be injected and used to measure the bounds of the browser viewport.

Virtual scrolling – The <cdk-virtual-scroll-viewport> displays large lists of elements performantly by only rendering the items that fit on-screen. Loading hundreds of elements can be slow in any browser; virtual scrolling enables a performant way to simulate all items being rendered by making the height of the container element the same as the height of total number of elements to be rendered, and then only rendering the items in view. Virtual scrolling is different from strategies like infinite scroll where it renders a set amount of elements and then when you hit the end renders the rest.

Text field

The text-field package provides useful utilities for working with text input fields such as <input> and <textarea>.

Automatically resizing a <textarea> – The cdkTextareaAutosize directive can be applied to any <textarea> to make it automatically resize to fit its content. The minimum and maximum number of rows to expand to can be set via the cdkAutosizeMinRows and cdkAutosizeMaxRows properties respectively.

The resize logic can be triggered programmatically by calling resizeToFitContent. This method takes an optional boolean parameter force that defaults to false. Passing true will force the <textarea> to resize even if its text content has not changed, this can be useful if the styles affecting the <textarea> have changed.

Go back to Tutorial

Virtual Scrolling and Drag and Drop
Angular 7 CDK Components

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?