@molecule/app-contact-form-angular

Feature · contact-form · App (browser) · v1.1.4 · Apache-2.0

Generic name + email + message form with submit handler

npm install @molecule/app-contact-form-angular

npm · Source on GitHub

How it works

@molecule/app-contact-form-angular is a ready-made contact-form 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 { ContactForm } from '@molecule/app-contact-form-angular'

@Component({
  selector: 'app-contact',
  standalone: true,
  imports: [ContactForm],
  template: `
    <mol-contact-form
      title="Get in touch"
      description="We'll respond within one business day."
      [onSubmit]="send"
    >
      <ng-template #success>
        <p>Thanks! We'll be in touch soon.</p>
      </ng-template>
    </mol-contact-form>
  `,
})
export class Contact {
  send = (values: Record<string, string>): Promise<void> => api.sendContactMessage(values)
}

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

Reference

Angular generic contact form — the counterpart of @molecule/app-contact-form-react: the same props and the same DOM for the same input.

Exports <ContactForm> and the ContactFormValues type: name + email + message fields with submit handling and success state, plus an extraFields slot for app-specific inputs.

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 { ContactForm } from '@molecule/app-contact-form-angular'

@Component({
  selector: 'app-contact',
  standalone: true,
  imports: [ContactForm],
  template: `
    <mol-contact-form
      title="Get in touch"
      description="We'll respond within one business day."
      [onSubmit]="send"
    >
      <ng-template #success>
        <p>Thanks! We'll be in touch soon.</p>
      </ng-template>
    </mol-contact-form>
  `,
})
export class Contact {
  send = (values: Record<string, string>): Promise<void> => api.sendContactMessage(values)
}

Type

feature

Installation

npm install @molecule/app-contact-form-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

ContactFormValues

Shape of values collected by the contact form and passed to onSubmit.

interface ContactFormValues {
  name: string
  email: string
  message: string
  /** App-supplied additional fields. */
  [key: string]: string
}

ContactFormProps

Props accepted by ContactForm — the same props @molecule/app-contact-form-react accepts. Node props (title, description, submitLabel, successContent) are TemplateRefs (or plain strings) in Angular; title, description and extraFields may also be projected as [slot=title], [slot=description] and [slot=extraFields] content.

interface ContactFormProps {
  /** Called with the form values on submit. Return a Promise to block double-submit. */
  onSubmit: (values: ContactFormValues) => void | Promise<void>
  /** Form heading. */
  title?: TemplateRef<unknown> | string | null
  /** Optional supporting copy under the heading. */
  description?: TemplateRef<unknown> | string | null
  /** Custom submit-button label. */
  submitLabel?: TemplateRef<unknown> | string | null
  /** Rendered when the form successfully submits. */
  successContent?: TemplateRef<unknown> | string | null
  /** Extra fields rendered above the message textarea. */
  extraFields?: TemplateRef<unknown> | string | null
  /** Extra classes. */
  className?: string
}

Classes

ContactForm

ContactForm component.

Generic name + email + message contact form with submit handling and success state; the app owns the side-effect via the onSubmit 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]); extraFields is projected content ([slot=extraFields]) rendered above the message textarea, as React renders it. The submit label and success content are inputs (TemplateRef or string), because their regions only exist inside conditional branches.

@Component({
  selector: 'mol-contact-form',
  standalone: true,
  imports: [Button, Input, Textarea, NgTemplateOutlet],
  hostDirectives: [MolPlacement],
  inputs: ['onSubmit', 'title', 'description', 'submitLabel', 'successContent', '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()"><header #headerEl [class]="headerClasses()"><h3 #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></h3><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></header><div mol-input [attr.aria-label]="nameLabel()" [id]="'contact-form-name'" [type]="'text'" [value]="name()" (change)="onNameChange($event)" [placeholder]="namePlaceholder()" [required]="true"></div><div mol-input [attr.aria-label]="emailLabel()" [id]="'contact-form-email'" [type]="'email'" [value]="email()" (change)="onEmailChange($event)" [placeholder]="emailPlaceholder()" [required]="true"></div><ng-content select="[slot=extraFields]"></ng-content><div mol-textarea [attr.aria-label]="messageLabel()" [id]="'contact-form-message'" [value]="message()" (change)="onMessageChange($event)" [placeholder]="messagePlaceholder()" [required]="true" [rows]="5"></div>@if (error()) {<p [class]="messageClasses()">{{ error() }}</p>}<button mol-button [type]="'submit'" [variant]="'solid'" [color]="'primary'" [disabled]="submitting()">@if (submitting()) {<ng-container>{{ sendingText() }}</ng-container>}@else if (submitLabelTemplate(); as tpl) {<ng-container [ngTemplateOutlet]="tpl" />}@else if (hasSubmitLabelText()) {<ng-container>{{ textOf(submitLabel) }}</ng-container>}@else {<ng-container>{{ sendText() }}</ng-container>}</button></form>}`,
})
export class ContactForm {
  onSubmit?: (values: Record<string, string>) => void | Promise<void>
  title?: TemplateRef<unknown> | string | null
  description?: TemplateRef<unknown> | string | null
  /** Custom submit-button label: text or template. */
  submitLabel?: TemplateRef<unknown> | string | null
  successContent?: TemplateRef<unknown> | string | null
  /** Extra classes. */
  className?: string

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

  private readonly i18n = useTranslation()

  private readonly host: ElementRef<HTMLElement> = inject(ElementRef)

  constructor() {
    // front of the host's place and the host leaves the page.
    usePlacement((hasContent) => {
      // would render nothing.
      const title = this.titleEl?.nativeElement
      const description = this.descriptionEl?.nativeElement
      const hasTitle =
        this.hasTitleText() || isTemplate(this.title) || (title ? hasContent(title) : false)
      const hasDescription =
        this.hasDescriptionText() ||
        isTemplate(this.description) ||
        (description ? hasContent(description) : false)
      setElementPresent(title, hasTitle)
      setElementPresent(description, hasDescription)
      setElementPresent(this.headerEl?.nativeElement, hasTitle || hasDescription)
      placeContentBefore(this.host.nativeElement, this.host.nativeElement)
      setElementPresent(this.host.nativeElement, false)
    })
  }

  /** The controlled name value. */
  protected readonly name = signal('')
  /** The controlled email value. */
  protected readonly email = signal('')
  /** The controlled message value. */
  protected readonly message = signal('')
  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()
  }

  textOf(value: unknown): string {
    return textOf(value)
  }

  titleTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.title) ? this.title : null
  }

  descriptionTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.description) ? this.description : null
  }

  submitLabelTemplate(): TemplateRef<unknown> | null {
    return isTemplate(this.submitLabel) ? this.submitLabel : null
  }

  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
  }

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

  hasSubmitLabelText(): boolean {
    return this.submitLabel !== undefined && this.submitLabel !== null
  }

  formClasses(): string {
    return this.cm().cn(this.cm().stack(3), this.className)
  }

  /** The heading's class (React's `cm.stack(1)`). */
  headerClasses(): string {
    return this.cm().stack(1)
  }

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

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

  namePlaceholder(): string {
    return this.i18n.t('contactForm.name', {}, { defaultValue: 'Your name' })
  }

  emailPlaceholder(): string {
    return this.i18n.t('contactForm.email', {}, { defaultValue: 'you@example.com' })
  }

  messagePlaceholder(): string {
    return this.i18n.t('contactForm.message', {}, { defaultValue: 'How can we help?' })
  }

  sendingText(): string {
    return this.i18n.t('contactForm.sending', {}, { defaultValue: 'Sending…' })
  }

  sendText(): string {
    return this.i18n.t('contactForm.send', {}, { defaultValue: 'Send message' })
  }

  nameLabel(): string {
    return this.i18n.t('contactForm.label.name', {}, { defaultValue: 'Name' })
  }

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

  messageLabel(): string {
    return this.i18n.t('contactForm.label.message', {}, { defaultValue: 'Message' })
  }

  onNameChange(event: Event): void {
    this.name.set((event.target as HTMLInputElement).value)
  }

  onEmailChange(event: Event): void {
    this.email.set((event.target as HTMLInputElement).value)
  }

  onMessageChange(event: Event): void {
    this.message.set((event.target as HTMLTextAreaElement).value)
  }

  async handle(event: Event): Promise<void> {
    event.preventDefault()
    if (this.submitting()) return
    this.submitting.set(true)
    this.error.set(null)
    try {
      await this.onSubmit?.({
        name: this.name(),
        email: this.email(),
        message: this.message(),
      })
      this.submitted.set(true)
      this.name.set('')
      this.email.set('')
      this.message.set('')
    } catch (err: unknown) {
      // so the ports call the same key for DOM parity.
      this.error.set(
        err instanceof Error
          ? err.message
          : this.i18n.t(
              'contactForm.error.submissionFailed',
              {},
              { defaultValue: 'Submission failed' },
            ),
      )
    } finally {
      this.submitting.set(false)
    }
  }
}

(Member comments are shortened to their first sentence, and the 40 longest are left out to fit; the full declaration is in node_modules/@molecule/app-contact-form-angular/dist/contact-form.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-contact-form for the placeholder / button strings in 79 languages.

onSubmit receives ONLY { name, email, message } — inputs rendered via the [slot=extraFields] projection are displayed but NOT collected; own their state in the parent and merge them inside your onSubmit. Always pass successContent: without it the form clears silently after a successful submit. If onSubmit throws, the thrown Error.message is shown verbatim below the form — throw translated, user-safe messages.

Node props are TemplateRefs or strings; title, description and extraFields may also be projected as [slot=title], [slot=description] and [slot=extraFields] content.

Translations

Translation strings are provided by @molecule/app-locales-contact-form.