@angular/cdk/portal package provides a way to render dynamic content in a target location. Portals are used extensively by the Overlay system.
Installation
Types of Portals
ComponentPortal
Render a component dynamically:TemplatePortal
Render a template dynamically:DomPortal
Move existing DOM elements:Portal Outlets
cdkPortalOutlet Directive
Programmatic Portal Attachment
Advanced Examples
Portal with Injector
Conditional Portal Rendering
Portal with Context
API Reference
ComponentPortal
TemplatePortal
DomPortal
Portal Methods
| Method | Returns | Description |
|---|---|---|
attach(host) | ComponentRef | EmbeddedViewRef | null | Attach portal to outlet |
detach() | void | Detach from outlet |
isAttached | boolean | Check if attached |
CdkPortalOutlet
Selector:[cdkPortalOutlet], [portalOutlet]
| Input | Type | Description |
|---|---|---|
cdkPortalOutlet | Portal<any> | Portal to attach |
| Method | Returns | Description |
|---|---|---|
attach(portal) | ComponentRef | EmbeddedViewRef | Attach portal |
detach() | void | Detach portal |
hasAttached() | boolean | Check if has portal |
Use Cases
Dynamic Tab Content
Reusable Modal Service
Best Practices
- Clean up - Detach portals when no longer needed
- Use typed contexts - For TemplatePortal type safety
- Provide injectors - For dependency injection in dynamic components
- Reuse portals - Detach/reattach instead of recreating
- Handle lifecycle - Components in portals have normal lifecycle