import { ChangeDetectionStrategy, Component, effect, inject, signal, untracked, viewChild, ViewEncapsulation, } from '@angular/core'; import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime'; import type { OpenInput } from '@embedpdf/angular/runtime'; import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage'; import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render'; import { withInteraction } from '@embedpdf/angular/interaction'; import { EpdfForm, EpdfFormLayer, toFieldRef, withForm } from '@embedpdf/angular/form'; import type { FormValidation } from '@embedpdf/angular/form'; import { localEngine } from '@embedpdf/engine'; // [!doc-source forms] const forms = async (): Promise => { const response = await fetch('https://www.embedpdf.com/pdfs/forms.pdf'); return { kind: 'bytes', id: 'forms', bytes: new Uint8Array(await response.arrayBuffer()) }; }; // [!/doc-source] @Component({ selector: 'demo-root', imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer], providers: [ provideEmbedPdf( { engine: () => localEngine(), initialDocuments: [{ source: forms }] }, withStage(), withRender(), withInteraction(), withForm(), ), ], changeDetection: ChangeDetectionStrategy.OnPush, styleUrl: './validate.css', encapsulation: ViewEncapsulation.None, template: `
@if (check(); as check) { @if (check.valid) { Every required field is filled in } @else { Fill in first: {{ missingNames(check) }} } }

Loading…

`, }) export class App { private readonly form = inject(EpdfForm); private readonly stage = viewChild(EpdfStage); private started = false; protected readonly check = signal(null); constructor() { // Fill in a name, then check the form, as if it was submitted. effect(() => { if (this.form.status() !== 'ready' || !this.stage() || this.started) return; this.started = true; untracked(() => { void this.form .setValue(toFieldRef('name'), { value: 'Ada Lovelace' }) .then(() => this.validate()); }); }); } /** Check the required fields. */ private validate() { const result = this.form.validate(); this.check.set(result); return result; } /** Submit: check, and put the cursor in the first empty field. */ protected submit() { const first = this.validate().missing[0]; if (first) this.form.focus(first.ref); } protected missingNames(check: FormValidation) { return check.missing.map((field) => field.name).join(', '); } }