@molecule/app-chart-wrapper-angular

Feature · chart-wrapper · App (browser) · v1.1.3 · Apache-2.0

Angular ChartCard and ChartLegend wrappers around @molecule/app-charts

npm install @molecule/app-chart-wrapper-angular

npm · Source on GitHub

How it works

@molecule/app-chart-wrapper-angular is a ready-made chart-wrapper feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.

import { Component } from '@angular/core'
import { ChartCard, ChartLegend, type ChartLegendItem } from '@molecule/app-chart-wrapper-angular'

@Component({
  selector: 'app-revenue-chart',
  standalone: true,
  imports: [ChartCard, ChartLegend],
  template: `
    <div mol-chart-card [minChartHeight]="240">
      <h3 slot="title">Monthly Revenue</h3>
      <p slot="description">Last 12 months</p>
      <canvas #canvas height="240"></canvas>
      <div slot="footer">
        <div mol-chart-legend [items]="items" (onToggle)="toggle($event)"></div>
      </div>
    </div>
  `,
})
export class RevenueChart {
  readonly items: ChartLegendItem[] = [
    { id: 'revenue', label: 'Revenue', color: 'var(--chart-1)' },
    { id: 'costs', label: 'Costs', color: 'var(--chart-2)' },
  ]

  readonly toggle = (id: string): void => {
    console.log('toggle series', id)
  }
}

Works with: @molecule/app-angular, @molecule/app-ui, @molecule/app-ui-angular

Reference

Angular ChartCard + ChartLegend wrappers around @molecule/app-charts — the counterpart of @molecule/app-chart-wrapper-react: the same props and the same DOM for the same input.

Exports:

  • <ChartCard> — uniform chrome (title / description / actions / summary / body / footer) around a chart rendering. minChartHeight (default 240) stops responsive charts collapsing; dataMolId sets data-mol-id.
  • <ChartLegend> — swatch + label (+ value) legend. Items become toggle buttons when onToggle is provided.
  • ChartLegendItem type.

These wrappers provide ONLY the surrounding chrome. The chart itself is whatever you project as the card's default content — typically a canvas driven by createLineChart/createBarChart from @molecule/app-charts (via a real bonded ChartProvider) or your own chart component. There is no <BarChart> component in @molecule/app-charts.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { Component } from '@angular/core'
import { ChartCard, ChartLegend, type ChartLegendItem } from '@molecule/app-chart-wrapper-angular'

@Component({
  selector: 'app-revenue-chart',
  standalone: true,
  imports: [ChartCard, ChartLegend],
  template: `
    <div mol-chart-card [minChartHeight]="240">
      <h3 slot="title">Monthly Revenue</h3>
      <p slot="description">Last 12 months</p>
      <canvas #canvas height="240"></canvas>
      <div slot="footer">
        <div mol-chart-legend [items]="items" (onToggle)="toggle($event)"></div>
      </div>
    </div>
  `,
})
export class RevenueChart {
  readonly items: ChartLegendItem[] = [
    { id: 'revenue', label: 'Revenue', color: 'var(--chart-1)' },
    { id: 'costs', label: 'Costs', color: 'var(--chart-2)' },
  ]

  readonly toggle = (id: string): void => {
    console.log('toggle series', id)
  }
}

Type

feature

Installation

npm install @molecule/app-chart-wrapper-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

ChartCardProps

Props accepted by ChartCard — the same props @molecule/app-chart-wrapper-react accepts. Node props (title, description, actions, summary, footer, children) are projected content in Angular (an input cannot carry an element), so they are typed unknown: pass them in the host template, not as values.

interface ChartCardProps {
  /** Card heading, projected as `[slot=title]` content (or a string input). */
  title?: unknown
  /** Optional supporting description, projected as `[slot=description]` content. */
  description?: unknown
  /** Optional right-aligned actions, projected as `[slot=actions]` content. */
  actions?: unknown
  /** Optional KPI summary row, projected as `[slot=summary]` content. */
  summary?: unknown
  /** Chart content, projected as the element's default content. */
  children?: unknown
  /** Optional footer, projected as `[slot=footer]` content. */
  footer?: unknown
  /** Set a minimum chart height so responsive charts don't collapse. Defaults to `240`. */
  minChartHeight?: number
  /** Extra classes on the Card. */
  className?: string
  /** `data-mol-id` for AI-agent selectors. */
  dataMolId?: string
}

ChartLegendItem

Describes a single series entry rendered in the chart legend.

interface ChartLegendItem {
  /** Series id — the value `onToggle` receives. */
  id: string
  /** Series label: plain text, or projected markup as a template reference. */
  label: string | number | TemplateRef<unknown>
  /** Swatch color (any valid CSS color or ClassMap token string). */
  color: string
  /** Optional value / count display next to the label. */
  value?: string | number | TemplateRef<unknown>
  /** Whether the series is hidden (greyed out). */
  hidden?: boolean
}

ChartLegendProps

Props accepted by ChartLegend.

interface ChartLegendProps {
  /** The legend's series. */
  items: ChartLegendItem[]
  /** Called when an item is toggled. */
  onToggle?: (id: string) => void
  /** Layout direction. Defaults to `'horizontal'`. */
  layout?: 'horizontal' | 'vertical'
  /** Extra classes. */
  className?: string
}

Classes

ChartCard

ChartCard component.

Uniform chrome around a chart rendering — header + actions + optional summary strip + chart body + optional footer. The host IS the Card div (div[mol-chart-card]), matching React's root exactly: React renders <Card className data-mol-id> whose Card defaults are variant elevated and padding md, so the host wears that same class list. The regions' content is projected content ([slot=title], [slot=description], [slot=actions], [slot=summary], [slot=footer], and the default slot).

This is the Angular counterpart of @molecule/app-chart-wrapper-react.

@Component({
  selector: 'div[mol-chart-card]',
  standalone: true,
  inputs: [
    'title',
    'description',
    'actions',
    'summary',
    'footer',
    'minChartHeight',
    'className',
    'dataMolId',
  ],
  hostDirectives: [MolPlacement],
  host: {
    '[class]': 'classes()',
    '[attr.data-mol-id]': 'dataMolId ?? null',
  },
  // prettier-ignore
  template: `<div [class]="stackClasses()"><header [class]="headerClasses()"><div [class]="titleBlockClasses()"><h3 [class]="titleClasses()">@if (hasTitle) {{{ title }}}<ng-content select="[slot=title]" /></h3><p #descriptionEl [class]="descriptionClasses()">@if (hasDescription) {{{ description }}}<ng-content select="[slot=description]" /></p></div><div #actionsEl [class]="actionsClasses()">@if (hasActions) {{{ actions }}}<ng-content select="[slot=actions]" /></div></header><div #summaryEl [class]="summaryClasses()">@if (hasSummary) {{{ summary }}}<ng-content select="[slot=summary]" /></div><div [style]="chartHeightStyle()"><ng-content></ng-content></div><div #footerEl>@if (hasFooter) {{{ footer }}}<ng-content select="[slot=footer]" /></div></div>`,
})
export class ChartCard {
  /** Card heading — a string input, or `[slot=title]` projected content. */
  title?: unknown
  /** Optional supporting description — a string input, or `[slot=description]` content. */
  description?: unknown
  /** Optional right-aligned actions — a string input, or `[slot=actions]` content. */
  actions?: unknown
  /** Optional KPI summary row — a string input, or `[slot=summary]` content. */
  summary?: unknown
  /** Optional footer — a string input, or `[slot=footer]` content. */
  footer?: unknown
  /** Minimum chart height. Defaults to `240` (React's default parameter). */
  minChartHeight?: number
  /** Extra classes on the Card. */
  className?: string
  /** `data-mol-id` for AI-agent selectors. */
  dataMolId?: string

  /** The description paragraph (always in the title block; detached while it has nothing to render). */
  @ViewChild('descriptionEl', { static: true })
  private descriptionEl?: ElementRef<HTMLParagraphElement>
  /** The actions row (always in the header; detached while it has nothing to render). */
  @ViewChild('actionsEl', { static: true }) private actionsEl?: ElementRef<HTMLDivElement>
  /** The summary strip (always in the stack; detached while it has nothing to render). */
  @ViewChild('summaryEl', { static: true }) private summaryEl?: ElementRef<HTMLDivElement>
  /** The footer (always in the stack; detached while it has nothing to render). */
  @ViewChild('footerEl', { static: true }) private footerEl?: ElementRef<HTMLDivElement>

  /**
   * Keeps each optional region on the page only while it renders a text input
   * or projected content, re-decided whenever either changes (a slot taken
   * away and given back included).
   */
  constructor() {
    usePlacement((hasContent) => {
      const description = this.descriptionEl?.nativeElement
      setElementPresent(
        description,
        this.hasDescription || (description ? hasContent(description) : false),
      )
      const actions = this.actionsEl?.nativeElement
      setElementPresent(actions, this.hasActions || (actions ? hasContent(actions) : false))
      const summary = this.summaryEl?.nativeElement
      setElementPresent(summary, this.hasSummary || (summary ? hasContent(summary) : false))
      const footer = this.footerEl?.nativeElement
      setElementPresent(footer, this.hasFooter || (footer ? hasContent(footer) : false))
    })
  }

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Whether a text title input renders (a projected title is not).
   * @returns True when the title input renders as text.
   */
  get hasTitle(): boolean {
    return this.title !== undefined && this.title !== null
  }

  /**
   * Whether a text description input renders (React's `description && …`).
   * @returns True when the description renders as text.
   */
  get hasDescription(): boolean {
    return (
      this.description !== undefined &&
      this.description !== null &&
      this.description !== false &&
      this.description !== ''
    )
  }

  /**
   * Whether a text actions input renders (React's `actions && …`).
   * @returns True when the actions render as text.
   */
  get hasActions(): boolean {
    return (
      this.actions !== undefined &&
      this.actions !== null &&
      this.actions !== false &&
      this.actions !== ''
    )
  }

  /**
   * Whether a text summary input renders (React's `summary && …`).
   * @returns True when the summary renders as text.
   */
  get hasSummary(): boolean {
    return (
      this.summary !== undefined &&
      this.summary !== null &&
      this.summary !== false &&
      this.summary !== ''
    )
  }

  /**
   * Whether a text footer input renders (React's `footer && …`).
   * @returns True when the footer renders as text.
   */
  get hasFooter(): boolean {
    return (
      this.footer !== undefined &&
      this.footer !== null &&
      this.footer !== false &&
      this.footer !== ''
    )
  }

  /**
   * The host's class list: the Card surface React renders (variant `elevated`,
   * padding `md`, not interactive) plus `className`.
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().card({ variant: 'elevated' }),
      this.cm().cardPadding('md'),
      this.className,
    )
  }

  /**
   * The body class (`cm.stack(4)`).
   * @returns The class string.
   */
  stackClasses(): string {
    return this.cm().stack(4)
  }

  /**
   * The header class (`cm.flex({ justify: 'between', align: 'start', gap: 'sm' })`).
   * @returns The class string.
   */
  headerClasses(): string {
    return this.cm().flex({ justify: 'between', align: 'start', gap: 'sm' })
  }

  /**
   * The title block class (`cm.stack(1)`).
   * @returns The class string.
   */
  titleBlockClasses(): string {
    return this.cm().stack(1)
  }

  /**
   * The title heading class (`cm.textSize('base')` + `cm.fontWeight('semibold')`).
   * @returns The class string.
   */
  titleClasses(): string {
    return this.cm().cn(this.cm().textSize('base'), this.cm().fontWeight('semibold'))
  }

  /**
   * The description class (`cm.textSize('sm')`).
   * @returns The class string.
   */
  descriptionClasses(): string {
    return this.cm().textSize('sm')
  }

  /**
   * The actions row class (`cm.flex({ align: 'center', gap: 'sm' })`).
   * @returns The class string.
   */
  actionsClasses(): string {
    return this.cm().flex({ align: 'center', gap: 'sm' })
  }

  /**
   * The summary strip class (`cm.flex({ align: 'center', gap: 'md', wrap: 'wrap' })`).
   * @returns The class string.
   */
  summaryClasses(): string {
    return this.cm().flex({ align: 'center', gap: 'md', wrap: 'wrap' })
  }

  /**
   * The chart body's inline style (React's `{ minHeight: minChartHeight }`,
   * default 240).
   * @returns The style attribute text.
   */
  chartHeightStyle(): string {
    return styleText({ minHeight: this.minChartHeight ?? 240 }) ?? ''
  }
}

ChartLegend

ChartLegend component.

Swatch + label (+ optional value) per series. When onToggle is provided, items become buttons that toggle series visibility. The host IS the legend div (div[mol-chart-legend]), matching React's root exactly.

This is the Angular counterpart of @molecule/app-chart-wrapper-react.

@Component({
  selector: 'div[mol-chart-legend]',
  standalone: true,
  imports: [NgTemplateOutlet],
  inputs: ['items', 'onToggle', 'layout', 'className'],
  host: {
    '[class]': 'classes()',
  },
  // prettier-ignore
  template: `<ng-template #row let-item><span [class]="contentClasses()"><span aria-hidden="true" [style]="swatchStyle(item)"></span><span [class]="labelClasses(item)" [style]="item.hidden ? 'opacity: 0.5' : null">@if (isNode(item.label)) {<ng-container [ngTemplateOutlet]="templateOf(item.label)"></ng-container>}@else {{{ textOf(item.label) }}}</span>@if (item.value !== undefined) {<span [class]="valueClasses()">@if (isNode(item.value)) {<ng-container [ngTemplateOutlet]="templateOf(item.value)"></ng-container>}@else {{{ textOf(item.value) }}}</span>}</span></ng-template>@for (item of items; track item.id) {@if (hasToggle()) {<button type="button" (click)="toggle(item.id)" [attr.aria-pressed]="!item.hidden"><ng-container [ngTemplateOutlet]="row" [ngTemplateOutletContext]="{$implicit: item}"></ng-container></button>}@else {<span><ng-container [ngTemplateOutlet]="row" [ngTemplateOutletContext]="{$implicit: item}"></ng-container></span>}}`,
})
export class ChartLegend {
  /** The legend's series. */
  items: ChartLegendProps['items'] = []
  /** Called when an item is toggled; when absent, items are plain spans. */
  onToggle?: (id: string) => void
  /** Layout direction. Defaults to `'horizontal'`. */
  layout?: 'horizontal' | 'vertical'
  /** Extra classes. */
  className?: string

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * Whether the items render as toggle buttons (React's `onToggle` presence).
   * @returns True when `onToggle` is set.
   */
  hasToggle(): boolean {
    return typeof this.onToggle === 'function'
  }

  /**
   * Calls `onToggle` for the clicked series.
   * @param id - The series id.
   */
  toggle(id: string): void {
    this.onToggle?.(id)
  }

  /**
   * Whether an item field is projected markup rather than plain text.
   * @param value - The field value.
   * @returns True for a template reference.
   */
  isNode(value: unknown): value is TemplateRef<unknown> {
    return value instanceof TemplateRef
  }

  /**
   * Narrows an item field to its template reference.
   * @param value - The field value.
   * @returns The template reference, or null for plain text.
   */
  templateOf(value: unknown): TemplateRef<unknown> | null {
    return value instanceof TemplateRef ? value : null
  }

  /**
   * Renders an item field as plain text.
   * @param value - The field value.
   * @returns The text.
   */
  textOf(value: unknown): string {
    return value === undefined || value === null ? '' : String(value)
  }

  /**
   * The legend's class list (React's flex classes plus `className`).
   * @returns The class string.
   */
  classes(): string {
    const cm = this.cm()
    return cm.cn(
      cm.flex({
        direction: this.layout === 'vertical' ? 'col' : 'row',
        align: 'center',
        gap: 'md',
        wrap: 'wrap',
      }),
      this.className,
    )
  }

  /**
   * The item content row class (`cm.flex({ align: 'center', gap: 'xs' })`).
   * @returns The class string.
   */
  contentClasses(): string {
    return this.cm().flex({ align: 'center', gap: 'xs' })
  }

  /**
   * The label class (React's `cm.textSize('sm')`, repeated when hidden).
   * @param item - The series entry.
   * @returns The class string.
   */
  labelClasses(item: ChartLegendItem): string {
    return this.cm().cn(
      this.cm().textSize('sm'),
      item.hidden ? this.cm().textSize('sm') : undefined,
    )
  }

  /**
   * The value class (`cm.textSize('sm')`).
   * @returns The class string.
   */
  valueClasses(): string {
    return this.cm().textSize('sm')
  }

  /**
   * The swatch's inline style (React's object).
   * @param item - The series entry.
   * @returns The style attribute text.
   */
  swatchStyle(item: ChartLegendItem): string {
    return (
      styleText({
        display: 'inline-block',
        width: 10,
        height: 10,
        borderRadius: 2,
        background: item.color,
        opacity: item.hidden ? 0.3 : 1,
      }) ?? ''
    )
  }
}

Injection Notes

Requirements

Peer dependencies:

  • @angular/common ^22.0.0
  • @angular/core ^22.0.0
  • @angular/platform-browser ^22.0.0
  • @molecule/app-angular ^3.13.0 || ^4.0.0
  • @molecule/app-ui ^1.0.1
  • @molecule/app-ui-angular ^1.1.0

Runtime Dependencies

  • @angular/common
  • @angular/core
  • @angular/platform-browser
  • @molecule/app-angular
  • @molecule/app-ui
  • @molecule/app-ui-angular

@molecule/app-charts' built-in provider renders a non-functional placeholder notice (and logs a one-time console warning), not a real chart. Bond the Chart.js provider once at startup — import { provider } from '@molecule/app-charts-chartjs'; setProvider(provider) — so createChart / createBarChart draw real charts (or render your own chart component as the default content). Legend items labels/values are plain text or projected template references; pass translated strings via t(). Node props are projected content: title, description, actions, summary and footer are selected by [slot=<name>], everything else lands in the chart body as the default projection.