@molecule/app-newsletter-signup-angular

Feature · newsletter-signup · App (browser) · v1.1.4 · Apache-2.0

Email + subscribe button with success state for newsletter capture

npm install @molecule/app-newsletter-signup-angular

npm · Source on GitHub

How it works

@molecule/app-newsletter-signup-angular is a ready-made newsletter-signup 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 { NewsletterSignup } from '@molecule/app-newsletter-signup-angular'

@Component({
  selector: 'app-subscribe',
  standalone: true,
  imports: [NewsletterSignup],
  template: `
    <mol-newsletter-signup
      title="Stay in the loop"
      description="Get weekly updates delivered to your inbox."
      layout="inline"
      [onSubscribe]="subscribe"
    >
      <ng-template>Thanks for subscribing!</ng-template>
    </mol-newsletter-signup>
  `,
})
export class Subscribe {
  subscribe = (email: string): Promise<void> => api.subscribe(email)
}

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

Reference

Angular email subscribe form — the counterpart of @molecule/app-newsletter-signup-react: the same props and the same DOM for the same input.

Exports <NewsletterSignup> with inline + stacked layouts. It tracks its own submitting / error / success state; the app owns the subscription side-effect via the onSubscribe input.

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 { NewsletterSignup } from '@molecule/app-newsletter-signup-angular'

@Component({
  selector: 'app-subscribe',
  standalone: true,
  imports: [NewsletterSignup],
  template: `
    <mol-newsletter-signup
      title="Stay in the loop"
      description="Get weekly updates delivered to your inbox."
      layout="inline"
      [onSubscribe]="subscribe"
    >
      <ng-template>Thanks for subscribing!</ng-template>
    </mol-newsletter-signup>
  `,
})
export class Subscribe {
  subscribe = (email: string): Promise<void> => api.subscribe(email)
}

Type

feature

Installation

npm install @molecule/app-newsletter-signup-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

NewsletterSignupProps

Props accepted by NewsletterSignup — the same props @molecule/app-newsletter-signup-react accepts. Node props (title, description, buttonLabel, successContent) are TemplateRefs (or plain strings) in Angular.

interface NewsletterSignupProps {
  /** Called with the email on submit. Return a Promise to block double-submit. */
  onSubscribe: (email: string) => void | Promise<void>
  /** Optional title above the form. */
  title?: TemplateRef<unknown> | string | null
  /** Optional supporting copy under the title. */
  description?: TemplateRef<unknown> | string | null
  /** Placeholder for the email input. */
  placeholder?: string
  /** Submit-button label. */
  buttonLabel?: TemplateRef<unknown> | string | null
  /** Rendered after successful subscription. */
  successContent?: TemplateRef<unknown> | string | null
  /** Layout — `'inline'` default (input + button on one row) or `'stacked'`. */
  layout?: 'inline' | 'stacked'
  /** Extra classes. */
  className?: string
}

Classes

NewsletterSignup

NewsletterSignup component.

Email + subscribe button widget, tracking its own submitting / error / success state; the app owns the subscription side-effect via the onSubscribe input. React's root element is a <form> while idle and a <div> once successContent renders, so the rendered root stands in front of the host's place and the host itself leaves the page (placeContentBefore + setElementPresent, React's fragment root).

The optional title and description are text inputs or projected content ([slot=title], [slot=description]); the success content is a successContent input (TemplateRef or string), because its wrapper only exists after a successful submit and projection capture points cannot be mounted conditionally.

@Component({
  selector: 'mol-newsletter-signup',
  standalone: true,
  imports: [Button, Input, NgTemplateOutlet],
  hostDirectives: [MolPlacement],
  inputs: [
    'onSubscribe',
    'title',
    'description',
    'placeholder',
    'buttonLabel',
    'successContent',
    'layout',
    'className',
  ],
  // by gluing the tags (see the ported unit tests).
  // prettier-ignore
  template: `@if (submitted() && successContent !== undefined) {<div [class]="className ?? null">@if (successTemplate(); as tpl) {<ng-container [ngTemplateOutlet]="tpl" />}@else if (successContent !== null) {<ng-container>{{ textOf(successContent) }}</ng-container>}</div>}@else {<form (submit)="handle($event)" [class]="formClasses()"><h4 #titleEl [class]="titleClasses()">@if (titleTemplate(); as tpl) {<ng-container [ngTemplateOutlet]="tpl" />}@else if (hasTitleText()) {<ng-container>{{ textOf(title) }}</ng-container>}<ng-content select="[slot=title]"></ng-content></h4><p #descriptionEl [class]="messageClasses()">@if (descriptionTemplate(); as tpl) {<ng-container [ngTemplateOutlet]="tpl" />}@else if (hasDescriptionText()) {<ng-container>{{ textOf(description) }}</ng-container>}<ng-content select="[slot=description]"></ng-content></p><div [class]="rowClasses()"><div mol-input [type]="'email'" [value]="email()" (change)="onEmailChange($event)" [placeholder]="placeholderText()" [required]="true" [attr.aria-label]="emailLabelText()" [className]="inputClass()"></div><button mol-button [type]="'submit'" [variant]="'solid'" [color]="'primary'" [disabled]="submitting()">@if (submitting()) {<ng-container>{{ subscribingText() }}</ng-container>}@else if (buttonLabelTemplate(); as tpl) {<ng-container [ngTemplateOutlet]="tpl" />}@else if (hasButtonLabelText()) {<ng-container>{{ textOf(buttonLabel) }}</ng-container>}@else {<ng-container>{{ subscribeText() }}</ng-container>}</button></div>@if (error()) {<p [class]="messageClasses()">{{ error() }}</p>}</form>}`,
})
export class NewsletterSignup {
  /** Called with the email on submit (React's `onSubscribe`). */
  onSubscribe?: (email: string) => void | Promise<void>
  /** Optional title above the form: text, or `[slot=title]` content. */
  title?: TemplateRef<unknown> | string | null
  description?: TemplateRef<unknown> | string | null
  /** Placeholder for the email input. */
  placeholder?: string
  /** Submit-button label: text or template. */
  buttonLabel?: TemplateRef<unknown> | string | null
  /** Rendered after successful subscription: text or template. */
  successContent?: TemplateRef<unknown> | string | null
  /** Layout — `'inline'` default or `'stacked'`. */
  layout?: 'inline' | 'stacked'
  /** Extra classes. */
  className?: string

  @ViewChild('titleEl') private titleEl?: ElementRef<HTMLElement>
  @ViewChild('descriptionEl') private descriptionEl?: ElementRef<HTMLElement>

  /** Reactive translation, read in the injection context. */
  private readonly i18n = useTranslation()

  /** The component's host element (React renders no element of its own). */
  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  constructor() {
    // nothing to render, as React's `{title && …}` renders no element.
    usePlacement((hasContent) => {
      placeContentBefore(this.host.nativeElement, this.host.nativeElement)
      setElementPresent(this.host.nativeElement, false)
      const title = this.titleEl?.nativeElement
      setElementPresent(
        title,
        this.hasTitleText() || isTemplate(this.title) || (title ? hasContent(title) : false),
      )
      const description = this.descriptionEl?.nativeElement
      setElementPresent(
        description,
        this.hasDescriptionText() ||
          isTemplate(this.description) ||
          (description ? hasContent(description) : false),
      )
    })
  }

  /** The controlled email value. */
  protected readonly email = signal('')
  /** Whether a submit is in flight (the button is disabled and busy). */
  protected readonly submitting = signal(false)
  /** Whether the last submit succeeded. */
  protected readonly submitted = signal(false)
  /** The last submit's error message. */
  protected readonly error = signal<string | null>(null)

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

  /** The text fallback used when a value is not a template. */
  textOf(value: unknown): string {
    return textOf(value)
  }

  /** The title as a template, when the caller passed a node. */
  titleTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.title) ? this.title : null
  }

  /** The description as a template, when the caller passed a node. */
  descriptionTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.description) ? this.description : null
  }

  /** The button label as a template, when the caller passed a node. */
  buttonLabelTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.buttonLabel) ? this.buttonLabel : null
  }

  /** The success content as a template, when the caller passed a node. */
  successTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.successContent) ? this.successContent : null
  }

  hasTitleText(): boolean {
    return typeof this.title === 'string'
      ? this.title !== ''
      : typeof this.title === 'number' && this.title !== 0
  }

  /** Whether the description input renders as text (React's truthiness). */
  hasDescriptionText(): boolean {
    return typeof this.description === 'string'
      ? this.description !== ''
      : typeof this.description === 'number' && this.description !== 0
  }

  hasButtonLabelText(): boolean {
    return this.buttonLabel !== undefined && this.buttonLabel !== null
  }

  /** The form's class list (React's `cm.cn(cm.stack(2), className)`). */
  formClasses(): string {
    return this.cm().cn(this.cm().stack(2), this.className)
  }

  /** The field row's class (React's inline flex, or the stacked column). */
  rowClasses(): string {
    return this.inline() ? this.cm().flex({ align: 'center', gap: 'sm' }) : this.cm().stack(2)
  }

  titleClasses(): string {
    return this.cm().cn(this.cm().textSize('sm'), this.cm().fontWeight('semibold'))
  }

  messageClasses(): string {
    return this.cm().textSize('sm')
  }

  /** The email field's extra class (React passes `cm.flex1` inline only). */
  inputClass(): string | undefined {
    return this.inline() ? this.cm().flex1 : undefined
  }

  inline(): boolean {
    return (this.layout ?? 'inline') === 'inline'
  }

  /** The email input's placeholder (React's default). */
  placeholderText(): string {
    return (
      this.placeholder ?? this.i18n.t('newsletter.placeholder', {}, { defaultValue: 'Your email' })
    )
  }

  subscribingText(): string {
    return this.i18n.t('newsletter.subscribing', {}, { defaultValue: 'Subscribing…' })
  }

  /** The button's idle text (React's `newsletter.subscribe`). */
  subscribeText(): string {
    return this.i18n.t('newsletter.subscribe', {}, { defaultValue: 'Subscribe' })
  }

  emailLabelText(): string {
    return this.i18n.t('newsletter.label.email', {}, { defaultValue: 'Email' })
  }

  /** Adopts the typed email (React's `onChange` on the controlled field). */
  onEmailChange(event: Event): void {
    this.email.set((event.target as HTMLInputElement).value)
  }

  async handle(event: Event): Promise<void> {
    event.preventDefault()
    if (this.submitting()) return
    this.submitting.set(true)
    this.error.set(null)
    try {
      await this.onSubscribe?.(this.email())
      this.submitted.set(true)
      this.email.set('')
    } catch (err: unknown) {
      this.error.set(
        err instanceof Error
          ? err.message
          : this.i18n.t(
              'newsletter.error.subscriptionFailed',
              {},
              {
                defaultValue: 'Subscription failed',
              },
            ),
      )
    } finally {
      this.submitting.set(false)
    }
  }
}

(Member comments are shortened to their first sentence, and the 16 longest are left out to fit; the full declaration is in node_modules/@molecule/app-newsletter-signup-angular/dist/newsletter-signup.component.d.ts.)

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

Requires a wired ClassMap bond and @molecule/app-angular's i18n provider above it — getClassMap() and useTranslation() both throw before wiring. Pair with @molecule/app-locales-newsletter-signup for the placeholder / button / label / error strings in 79 languages.

ALWAYS pass successContent — without it a successful submit only clears the input and re-renders the empty form (no built-in "thanks" message). Return a Promise from onSubscribe so double-submits are blocked while in flight; a rejected Promise renders the error's message verbatim below the form, so throw user-readable (ideally pre-translated) messages.

Translations

Translation strings are provided by @molecule/app-locales-newsletter-signup.