In the Angular CDK portal package, what do ComponentPortal, TemplatePortal and DomPortal each wrap, and when do you pick each one?
answer
- what the content already is
- class, template or existing element
- template needs a ViewContainerRef
- moved DOM loses live bindings
- cdkPortal and cdkPortalOutlet
basics
~20 sComponentPortal wraps a component class that is created on attach, TemplatePortal wraps an ng-template plus a ViewContainerRef, and DomPortal moves an existing DOM element as it is. Pick the one that matches what your content already is.
solid answer
~40 sIn `@angular/cdk/portal`, a portal is a piece of UI that a `PortalOutlet` renders somewhere else. `new ComponentPortal(CellEditor)` creates the component only when it is attached, so it suits self-contained content; you may also pass a `ViewContainerRef` and an `Injector`. `new TemplatePortal(templateRef, viewContainerRef, context?)` renders an `<ng-template>` declared in the host's own template, so its bindings keep reading the host component's fields; the `cdkPortal` directive is a ready-made `TemplatePortal`. `new DomPortal(elementRef)` moves an element that already exists and puts it back when detached, but because it moves raw DOM, Angular bindings inside it may stop updating. On the receiving side, `cdkPortalOutlet` is the in-template outlet and an `OverlayRef` from the CDK overlay is the floating one.
go deeper
Recall the three classes by what they wrap: a component class, a template with its ViewContainerRef, or an element that already exists. Know that cdkPortal makes a portal and cdkPortalOutlet receives one.
Explain where each portal's content lives logically versus where it renders, why a template keeps its declaring component's bindings, and why DomPortal can leave bindings stale.
Choose the portal kind from ownership of state and lifetime: a component for reusable editors, a template when the host owns the data, and DomPortal only for static markup. Mention the one-portal-per-outlet rule.
Frame portals as the seam that lets a component library separate content from placement, so overlays, side panels and in-page slots share one content contract instead of three ad hoc ones.
## What a portal is in the Angular CDK The `@angular/cdk/portal` package splits rendering into two halves: - a **portal** is the *piece of UI* you want to show; - a **portal outlet** is the *open slot* where it appears. The point of the split is that the code deciding *what* to render and the code deciding *where* it lands can live in different places. The CDK overlay is built on this: an `OverlayRef` *is* a portal outlet, so anything you can wrap in a portal can be floated above the page. Every portal has `attach(outlet)`, `detach()` and an `isAttached` flag, and every outlet has `attach(portal)`, `detach()`, `dispose()` and `hasAttached()`. ## The three portal classes | Class | Wraps | Created when | Typical use | |---|---|---|---| | `ComponentPortal` | a component class | on attach | a self-contained editor, panel or widget | | `TemplatePortal` | a `TemplateRef` plus a `ViewContainerRef` (and an optional context) | on attach | markup declared next to the code that owns its data | | `DomPortal` | an existing element (`ElementRef` or `HTMLElement`) | already exists; it is moved | relocating markup that is already on the page | **`ComponentPortal`** takes the component type first. Its optional arguments are a `ViewContainerRef` (where the component sits in Angular's *logical* tree, which is separate from where it *renders*), an `Injector`, projectable nodes for `<ng-content>`, and in recent versions bindings and directives. Nothing is instantiated until an outlet attaches it. **`TemplatePortal`** needs the template *and* a `ViewContainerRef`; the context object becomes the template's `let-` variables. Because an Angular template is bound where it was declared, the content keeps reading the declaring component's fields and calling its methods even though it renders elsewhere. **`DomPortal`** does not create anything. It inserts a comment where the element was, moves the element into the outlet, and on detach puts the element back at that comment. The CDK guide warns that it moves content *as is*, so bindings or directives inside it may no longer update. ## Declarative helpers: cdkPortal and cdkPortalOutlet Two directives let you skip the constructors: 1. `<ng-template cdkPortal>` (or `*cdkPortal` on an element) turns the template into a `TemplatePortal`. The `CdkPortal` class extends `TemplatePortal`, so a parent reads it with a view query and hands it to any outlet. 2. `<ng-template [cdkPortalOutlet]="portal">` is an outlet in a template. Assigning a different portal swaps the content; assigning `null` clears it. Its `attached` output emits the created `ComponentRef` or `EmbeddedViewRef`. ```html <ng-template cdkPortal #help="cdkPortal"> <p>Use = to start a formula.</p> </ng-template> <aside> <ng-template [cdkPortalOutlet]="helpVisible() ? help : null" /> </aside> ``` ## Logical location versus rendered location A portal's DOM lands in the outlet, but its place in Angular's tree can be elsewhere, and that decides which injector and which change-detection parent it gets: - A `ComponentPortal` with a `ViewContainerRef` is created in that container, so it inherits the injector of the component that owns the container. - A `ComponentPortal` without one, attached to a CDK overlay, is created on its own and attached to the application, resolving dependencies from the injector the overlay was created with unless the portal brings its own `Injector`. - Attached to `cdkPortalOutlet` without its own container, it is created in the outlet's container instead. - A `TemplatePortal` attached to an overlay creates its embedded view in the `ViewContainerRef` you gave it, then moves the nodes into the pane. ## Choosing one in a spreadsheet grid Picture a spreadsheet-like grid with a cell editor and a column-filter panel: - The **cell editor** is its own component with inputs, validation and keyboard handling, so a `ComponentPortal` of it is natural. The grid creates the portal when a cell enters edit mode. - The **column-filter panel** is a few checkboxes whose state lives in the grid component. Declaring it as an `<ng-template>` in the grid's template and wrapping it in a `TemplatePortal` keeps the bindings next to the data they read. - A **DomPortal** fits only when the markup already exists and has no live Angular bindings you depend on, such as a static legend you move into a side panel. ## Pitfalls worth knowing - An outlet holds one portal at a time: attaching a second without detaching the first throws `Host already has a portal attached` in development mode. - A `TemplatePortal` cannot be built without a `ViewContainerRef`; inject one in the declaring component. - `DomPortal` throws if the element has no parent node, because it needs a place to leave its anchor comment. - Portals describe content only. Position, backdrop and scroll behaviour belong to whatever outlet receives them, such as the CDK overlay. - The old `TemplatePortalDirective` and `PortalHostDirective` names are gone; `CdkPortal` and `CdkPortalOutlet` replaced them.
- If a TemplatePortal renders inside an overlay attached to the page body, which component's fields do its bindings read?The component that declared the `<ng-template>`. An Angular template is bound where it is declared, so the embedded view reads that component's fields and methods even though its DOM nodes are moved into the overlay pane. That is why a filter panel declared in the grid's template can bind straight to the grid's filter state.
- What happens if you assign a new portal to a cdkPortalOutlet that already shows one?The outlet detaches the current portal first, destroying its component or embedded view, and then attaches the new one. Binding `[cdkPortalOutlet]` to an expression is therefore a clean way to switch content; binding it to `null` simply clears the slot.
A portal is a framed picture and the outlet is the hook on the wall: the frame says what you see, the hook says where it hangs. A ComponentPortal is a print made to order when you hang it, a TemplatePortal is a picture painted in your own studio that keeps its colours from there, and a DomPortal is a picture taken off another wall, which goes back to that wall when you take it down.
- A DomPortal re-renders its content, so Angular bindings keep working.
- A TemplatePortal can be built from a TemplateRef alone.
- A ComponentPortal creates its component as soon as you call new.
- cdkPortalOutlet is the directive that turns a template into a portal.
- One outlet can show several attached portals at once.