Skip to main content
XenonStack

Service Design

XenonStack Insights Reusable Angular Components: ng-content, Templates, Dynamic

and | Published | Updated

Featured image titled Reusable Angular components, with a stack from standalone components through inputs and slots to consistent shared UI

Key takeaway

  • How to build reusable Angular components with ng-content, ng-template, signals and standalone components, plus when not to reuse and how to govern them.

What are reusable Angular components?

A reusable Angular component defines a fixed structure and behaviour once, and lets each parent supply the parts that change, such as its content, a template or a few inputs. Buttons, loaders, tabs, dropdowns and search bars are the usual examples. The parent decides what goes in; the reusable component decides how it looks and behaves.

For enterprise teams the point is control. When a shared component changes, every screen that uses it changes with it, which keeps interfaces consistent and cuts duplicated work. The cost is coupling, so reuse should be deliberate. For related reading, see our guides to Angular performance optimisation and Angular dependency injection.

What levels of reuse can a component offer?

LevelWhat the parent controlsTypical Angular mechanism
TemplatingNothing; the markup is sharedOne component used in many places
ConfigurationVariations such as loading or disabled stateInputs
AdaptabilityContent placed in slotsng-content with select
InversionHow each item is renderedng-template with ngTemplateOutlet and context
Extension and nestingBehaviour added through a hierarchyInheritance, host directives, compound components

Start at the lowest level that solves the problem. Moving up the table gives the parent more power and the component author more to maintain.

How do inputs make a component configurable?

According to angular.dev, input() declares an input and returns a read-only signal. input.required() makes the input mandatory and raises a build-time error if a parent omits it. The older @Input decorator remains fully supported, and the Angular team recommends input() for new projects.

Two-column diagram mapping what a parent needs (state changes, own content, row control, shared state) to Angular mechanisms (inputs, ng-content with select, ng-template with context, compound components)
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-button',
  template: `<button [disabled]="disabled() || loading()">
    @if (loading()) { Loading... } @else { <ng-content /> }
  </button>`,
})
export class AppButton {
  readonly loading = input(false);
  readonly disabled = input(false);
}

The documentation also advises against input names that collide with DOM element properties and against prefixing input names. Use a transform such as booleanAttribute when templates should be able to write <app-button disabled>.

How does content projection work with ng-content?

The <ng-content> element marks where the parent's content appears. Angular's content projection guide says it is neither a component nor a DOM element, so you cannot insert, remove or modify it at run time. Content you place inside <ng-content> is shown as fallback when the parent supplies nothing.

@Component({
  selector: 'app-panel',
  template: `<h2><ng-content>Untitled</ng-content></h2>`,
})
export class Panel {}

<app-panel>Quarterly report</app-panel>

How do I use several slots with select?

Give each placeholder a select attribute that uses the same CSS selectors as component selectors. A placeholder without select captures everything not matched elsewhere. If there is no catch-all, unmatched elements do not render into the DOM. The order in the parent does not matter; the order of the placeholders in the child decides the output.

@Component({
  selector: 'app-card',
  template: `
    <header><ng-content select="[card-title]" /></header>
    <ng-content />
    <footer><ng-content select="[card-footer]" /></footer>`,
})
export class Card {}

<app-card>
  <h3 card-title>Invoice 1042</h3>
  <p>Body content</p>
  <a card-footer href="/invoices">Back</a>
</app-card>

The guide notes that select sees only static attributes and classes. A dynamic binding such as [class.within] is not matched. ngProjectAs lets an element match a different selector, but only with a static value.

When should I use ng-template instead of ng-content?

Questionng-contentng-template with ngTemplateOutlet
Who creates the content?The parent, once, in its own viewThe child, when and as often as it chooses
Can the child pass data back?NoYes, through the template context
Good fitCards, panels, buttons, layout shellsLists, tables and menus with custom rows or cells
Conditional displayDo not wrap in @if, @for or @switchRender the template only when needed

The content projection guide warns that Angular always instantiates and creates DOM nodes for content sent to an <ng-content> placeholder, even if the placeholder is hidden. It also says projected content belongs to the parent's view, so a child using OnPush does not skip it. For content that must render conditionally, use a template.

How do I let the parent control how each item renders?

The NgTemplateOutlet directive, documented on angular.dev, inserts an embedded view from a prepared TemplateRef. Its ngTemplateOutletContext input supplies values to the template; the $implicit key becomes the default let value.

@Component({
  selector: 'app-list',
  imports: [NgTemplateOutlet],
  template: `
    @for (item of items(); track item.id) {
      <ng-container
        *ngTemplateOutlet="rowTemplate() ?? fallback; context: { $implicit: item }" />
    }
    <ng-template #fallback let-item>{{item.name}}</ng-template>`,
})
export class AppList {
  readonly items = input.required<Item[]>();
  readonly rowTemplate = input<TemplateRef<{ $implicit: Item }>>();
}

<app-list [items]="rows" [rowTemplate]="row" />
<ng-template #row let-item><strong>{{item.name}}</strong></ng-template>

The child owns the loop and the fallback; the parent owns the look of each row. That split is what makes a list, table or dropdown reusable across teams.

How do compound components share state?

A compound component is a set of small components that work together, such as a toggle with an on label, an off label and a button. The parent component holds the state and the children read it through dependency injection, so the page author arranges them freely.

@Component({ selector: 'app-toggle', template: `<ng-content />` })
export class Toggle {
  readonly on = signal(false);
  flip() { this.on.update(v => !v); }
}

@Component({
  selector: 'app-toggle-button',
  template: `<button (click)="toggle.flip()" [attr.aria-pressed]="toggle.on()"><ng-content /></button>`,
})
export class ToggleButton { protected toggle = inject(Toggle); }

@Component({
  selector: 'app-toggle-on',
  template: `<span [hidden]="!toggle.on()"><ng-content /></span>`,
})
export class ToggleOn { protected toggle = inject(Toggle); }

<app-toggle>
  <app-toggle-button>Switch theme</app-toggle-button>
  <app-toggle-on>Day</app-toggle-on>
</app-toggle>

Here [hidden] is used instead of wrapping <ng-content> in @if, in line with the guidance above. If a parent needs a direct reference to projected children, the queries guide describes contentChild and contentChildren. Signal queries are recommended for new projects, and decorator queries remain fully supported. Decorator results are undefined until ngAfterContentInit, and queries never reach into other components' templates.

How do I create components dynamically?

angular.dev describes two main routes. NgComponentOutlet renders a component chosen at run time from a template. ViewContainerRef.createComponent does the same from TypeScript and takes the component type directly, with an optional bindings array that includes inputBinding. For an embedded template, createEmbeddedView takes a TemplateRef and an optional context. For lazy loading, the page recommends @defer first and a dynamic import() as the fallback. Binding support depends on your Angular version, so confirm on the official page.

private host = inject(ViewContainerRef);

add() {
  this.host.createComponent(WidgetInput, {
    bindings: [inputBinding('message', () => 'Added from code')],
  });
}

What do standalone components change?

The Angular components guide says components are standalone by default and are added directly to the imports array of the component that uses them. It names 19.0.0 as the version where that default changed; before it, the standalone option defaulted to false and components were imported through their NgModule. For a shared library this means each reusable component lists what it needs, so a consumer imports one symbol rather than a whole module. angular.dev's version page lists 20.x, 21.x and 22.x as actively supported at the time of writing (read 13 November 2026); check it before choosing a baseline.

When should a component not be reusable?

SituationBetter choiceWhy
Used on one screen, no second use in sightKeep it localGeneralising early adds inputs and slots nobody uses
Every use needs different markupTemplate-driven slot or separate componentsA long input list becomes a hidden configuration language
Parent and child share business rulesA service, injected into bothPresentation stays separate from logic
Needs to be used by several teamsShared library with versioning and an ownerBreaking changes affect everyone

Reusable components improve efficiency and consistency, but not every component should be reusable. Over-generalising leads to tightly coupled code that is hard to maintain.

How should enterprise teams govern a shared component library?

  • Ownership: name a team that reviews changes to shared components and publishes release notes.
  • Testing: test a component against its own contract. Our guide to unit testing covers the practice in general.
  • Accessibility: build roles and states, such as aria-pressed above, into the shared component once.
  • Cost: track how many screens depend on each component, so a change is sized before it ships.
  • AI-assisted code: when agents generate or review components, check output against the same standards. ElixirData Context OS keeps governed context, versioned policy and decision traces in one decision layer above AI agents, and AgentQA offers quality assurance for agent workflows and outputs.

What is a sensible adoption sequence?

  1. List the interface elements that already appear three or more times.
  2. Extract the simplest one with inputs and a single ng-content slot.
  3. Add named slots only when a second team needs a different layout.
  4. Move to templates and context where the child must pass data back.
  5. Publish the set as a library with an owner, tests and release notes.

New to the framework? Our Angular learning path for React developers is a good starting point.

To map one front-end decision your agents should make, and the context and policy it depends on, book a Context Workshop. See what happens in the workshop.

Frequently asked questions

What is the difference between ng-content and ng-template?

With ng-content the parent creates the content and the child only places it. With ng-template the child decides when and how often to render the template and can pass data through its context.

Can I conditionally show ng-content with @if?

Angular's guide advises against it, because Angular still creates the projected DOM nodes even when the placeholder is hidden. Use a template for content that must render conditionally.

Do I need NgModules for reusable components?

Not in recent versions. Components are standalone by default from Angular 19.0.0 and are imported through the imports array.

Should I use input() or @Input?

Both are supported. angular.dev recommends input() for new projects, and input.required() gives a build-time error when a required value is missing.

How do I render a component from code?

Inject ViewContainerRef and call createComponent with the component type, or use NgComponentOutlet in the template.

Ready to put AI agents to work? See an ElixirClaw demo: the agentic OS to build, orchestrate and govern AI agents across your enterprise systems.

Table of Contents

navdeep-singh-gill

Navdeep Singh Gill

Global CEO and Founder of XenonStack

LinkedIn profile

Navdeep Singh Gill is serving as Chief Executive Officer and Product Architect at XenonStack. He holds expertise in building SaaS Platform for Decentralised Big Data management and Governance, AI Marketplace for Operationalising and Scaling. His incredible experience in AI Technologies and Big Data Engineering thrills him to write about different use cases and its approach to solutions.

Get the latest articles in your inbox

Subscribe Now

Interested in solving your challenges with the XenonStack team?
Get Started

Tell us about you and your priorities so we can prepare the right conversation. It takes about 2 minutes.

Please Select your Industry
Banking
Fintech
Payment Providers
Wealth Management
Discrete Manufacturing
Semiconductor
Machinery Manufacturing / Automation
Appliances / Electrical / Electronics
Elevator Manufacturing
Defense & Space Manufacturing
Computers & Electronics / Industrial Machinery
Motor Vehicle Manufacturing
Food and Beverages
Distillery & Wines
Beverages
Shipping
Logistics
Mobility (EV / Public Transport)
Energy & Utilities
Hospitality
Digital Gaming Platforms
SportsTech with AI
Public Safety - Explosives
Public Safety - Firefighting
Public Safety - Surveillance
Public Safety - Others
Media Platforms
City Operations
Airlines & Aviation
Defense Warfare & Drones
Robotics Engineering
Drones Manufacturing
AI Labs for Colleges
AI MSP / Quantum / AGI Institutes
Retail Apparel and Fashion

Continue