Embed a form builder with Angular
Tags: angular, forms, sdk, javascript
Published: 2024-04-11 00:56:40

In this guide, we'll show how to embed a form builder with Angular using the [Joyfill JS forms SDK](https://docs.joyfill.io/docs/javascript), and offer a world-class form solution in minutes.

You can think of Joyfill as a sort of Stripe or Twilio, but for forms.

### How to embed a form builder with Angular + Joyfill

**Step 1: Create Joyfill Account**

**Step 2: Generate Your `userAccessToken`**

**Step 3: Create Your First Template**

**Step 4: Get your template `identifier`**

**Step 5: Install**

If you don't need a tutorial and just want to get started, please consider reading the [quickstart docs](https://docs.joyfill.io/docs/setup) instead.

### Why Joyfill’s embeddable form builder?

Forms require a lot more engineering time, resources, and ongoing maintenance than you would first expect. Building a flexible, reliable, and scalable form solution is hard, time-consuming, and comes with a lot of unknown features. Conditional logic, revision management, multi-device compatibility, user collaboration, field validation, export engine, template library, just to name a few.

This is where we come in. With Joyfill you can deploy a form builder in under 15 minutes, and we take care of all of the above and more.

### Requirements

- Angular v17+
- [Review SDK README](https://www.npmjs.com/package/@joyfill/components)

### The Prerequisites

The steps below are the prerequisites you will need to accomplish before moving on to the rest of this Angular guide.

### Step 1: Create Joyfill Account

To begin working with Joyfill, go to [Joyfill's Platform](http://app-joy.joyfill.io/) and create an account (*jump to step 2 if you already have an account*). By creating an account you will add yourself as the first user to your newly created Joyfill Organization and be placed inside the Joyfill Manager.

### Step 2: Generate Your `userAccessToken`

Once you're inside the Joyfill Manager you will want to select from the top navigation bar Settings & Users -> Manager Users -> and click "Access Tokens" button next to your user. Once the modal appears select "Add Access Token". Copy and securely store your access token for later use.

### Step 3: Create Your First Template

Create your first template within the Joyfill Manager by going to the [Template Library](https://app-joy.joyfill.io/library) tab in the top navigation and click the "Add Template".

We recommended following this guide [Create Your First Template](https://docs.joyfill.io/docs/how-to-create-templates) when creating your first template. This makes it easy to experiment with the different parts of the Joyfill Platform easily.

### Step 4: Get your template `identifier`

Inside the Joyfill Manager you will want to select from the top navigation bar [Template Library](https://app-joy.joyfill.io/library) and under your Templates table list within the column `ID` copy that for pasting into our example Angular/JS guides.

### 5. Install

**NPM:**

```jsx
npm install --save @joyfill/components
```

**Yarn:**

```jsx
yarn add @joyfill/components
```

### 6. Usage

- Add the Template identifier from the previous setup step to the `app.component.ts` file.
- Add the User Access Token from the preview setup step to the `joyfill.service.ts` file.
- **❗️Important Note:** ensure you use the full import path `import { JoyDoc } from '@joyfill/components/dist/joyfill.min.js'`. This will ensure proper angular support.

**app.component.ts:**

```jsx
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { JoyDoc } from '@joyfill/components/dist/joyfill.min.js';

import { JoyfillService } from './joyfill.service';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  template: `
    <main>
      <header>
        <button (click)="handleSave()">Save</button>
      </header> 
      <div id="joyfill-target"></div>
    </main>
  `,
  styleUrl: './app.component.css'
})

export class AppComponent implements OnInit {

  joyfillService: JoyfillService = inject(JoyfillService);
  
  identifer = '<REPLACE WITH YOUR TEMPLATE IDENTIFIER>';
  pendingTemplate = {};

  ngOnInit() {
    this.initJoyfill();
  }

  async initJoyfill() { 

    const template = await this.joyfillService.getTemplate(this.identifer);

    JoyDoc(
      document.getElementById('joyfill-target'),
      {
        doc: template,
        onChange: (changelogs, data) => {
          /**
           * changelogs - the individual changes
           * data - the entire new template with all changes applied
           */
          console.log(changelogs, data)
          this.pendingTemplate = data;
        }
      }
    );

  }

  async handleSave() {
    const updatedTemplate = await this.joyfillService.updateTemplate(this.identifer, this.pendingTemplate);
    console.log('>>>>>>>>>>> updatedTemplate: ', updatedTemplate);
  }

}
```

**joyfill.service.ts:**

```jsx
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class JoyfillService {

  url = 'https://api-joy.joyfill.io/v1';

  headers = { 
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <REPLACE WITH YOUR USER ACCESS TOKEN>'
  }

  constructor() { }

  async getTemplate(identifier: string): Promise<object> {

    const data = await fetch(`${this.url}/templates/${identifier}`, {
      method: 'GET',
      headers: this.headers
    });
    
    return await data.json();

  }

  async updateTemplate(identifier: string, data: object): Promise<object> {
    
    const response = await fetch(`${this.url}/templates/${identifier}`, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify(data)
    });

    return await response.json();

  }

}
```

### Typescript

We have added the properties below to the "compilerOptions" in the tsconfig.json file in order to support the Joyfill JS SDK.

```
"allowJs": true,
"noImplicitAny": false
```

### **Angular form builder guide summary**

This guide serves as a comprehensive walkthrough for seamlessly integrating the Joyfill JS forms SDK into an Angular application to create an embeddable form builder. Joyfill simplifies the intricate and time-consuming process of form development.

Key steps in the guide include creating a Joyfill account, generating a user access token, and crafting an initial form template within the Joyfill Manager. The obtained template identifier is pivotal for the integration process, and users are directed to install Joyfill components using npm or yarn.

Usage instructions facilitate the incorporation of the Joyfill form builder into the Angular application. Details include adding the template identifier to the app.component.ts file and the user access token to the joyfill.service.ts file. TypeScript configurations in the tsconfig.json file are advised for optimal compatibility with the Joyfill JS SDK.

Providing code snippets for reference, the guide emphasizes the efficiency of Joyfill in managing complex form features such as conditional logic, revision management, and multi-device compatibility. The recommended Angular version is specified as v17+, and users are encouraged to consult the SDK README for additional insights. Overall, this guide streamlines the process, enabling users to deploy a robust form builder within their Angular application in just a few steps.

### Try it yourself

If you’re looking for a full example project that shows many more of the Joyfill SDK capabilities and workflows then head over to our full example project and try it for yourself.

- [Joyfill Angular Example](https://github.com/joyfill/examples/tree/main/angular)
- [SDK NPM Package](https://www.npmjs.com/package/@joyfill/components)