Documentation Docs
Documentation Docs

Add Survey Creator / Form Builder to an Angular Application

This step-by-step tutorial will help you get started with the Survey Creator component in an Angular application. To add the component to your application, follow the steps below:

View Full Code on GitHub

If you are looking for a quick-start application that enables all Survey Creator features, refer to the following GitHub repository: Angular CLI + SurveyJS Quick Start Boilerplate.

Install the survey-creator-angular npm Package

Survey Creator for Angular consists of two npm packages: survey-creator-core (platform-independent code) and survey-creator-angular (rendering code). Run the following command to install survey-creator-angular. The survey-creator-core package will be installed automatically as a dependency.

npm install survey-creator-angular --save

SurveyJS for Angular requires Angular v12.0.0 or newer and depends on the @angular/cdk package. If your project does not include it yet, run the following command:

npm install @angular/cdk@^12.0.0 --save

Earlier Angular versions are supported by the survey-creator package. It depends on Knockout and is now obsolete. However, you can use it in your Angular v8–v11 projects. Refer to the following examples on GitHub for more information:

Configure Styles

Open the angular.json file and reference Survey Creator and SurveyJS Form Library style sheets:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  // ...
  "projects": {
    "project-name": {
      "projectType": "application",
      // ...
      "architect": {
        "build": {
          // ...
          "options": {
            // ...
            "styles": [
              "src/styles.css",
              "node_modules/survey-core/defaultV2.min.css",
              "node_modules/survey-creator-core/survey-creator-core.min.css"
            ],
            // ...
          }
        }
      }
    }
  }
}

Note that although standalone surveys support multiple predefined themes, surveys within Survey Creator apply only one theme ("Default V2"). However, you can use the survey configuration (JSON object) produced by Survey Creator to build a standalone survey and apply any theme to it. You can also customize Survey Creator theme colors as shown in the following example:

View Demo

Configure Survey Creator

To configure the Survey Creator component, specify its properties in a configuration object. In this tutorial, the object enables the following properties:

  • showLogicTab
    Displays the Logic tab in the tab panel.

  • isAutoSave
    Automatically saves the survey JSON schema on every change.

const creatorOptions = {
  showLogicTab: true,
  isAutoSave: true
};

Pass the configuration object to the SurveyCreatorModel constructor as shown in the code below to instantiate Survey Creator. Assign the produced instance to a component property that will be used later to render Survey Creator:

import { Component, OnInit } from '@angular/core';
import { SurveyCreatorModel } from "survey-creator-core";

@Component({
  selector: 'survey-creator-component',
  templateUrl: './survey-creator.component.html',
  styleUrls: ['./survey-creator.component.css']
})
export class SurveyCreatorComponent implements OnInit {
  surveyCreatorModel: SurveyCreatorModel;
  ngOnInit() {
    const creator = new SurveyCreatorModel(creatorOptions);
    this.surveyCreatorModel = creator;
  }
}
View Full Code
import { Component, OnInit } from "@angular/core";
import { SurveyCreatorModel } from "survey-creator-core";

const creatorOptions = {
  showLogicTab: true,
  isAutoSave: true
};

@Component({
  selector: 'survey-creator-component',
  templateUrl: './survey-creator.component.html',
  styleUrls: ['./survey-creator.component.css']
})
export class SurveyCreatorComponent implements OnInit {
  surveyCreatorModel: SurveyCreatorModel;
  ngOnInit() {
    const creator = new SurveyCreatorModel(creatorOptions);
    this.surveyCreatorModel = creator;
  }
}

Render Survey Creator

Before you render the survey, you need to import the module that integrates Survey Creator with Angular. Open your NgModule class (usually resides in the app.module.ts file), import the SurveyCreatorModule from survey-creator-angular, and list it in the imports array.

// app.module.ts
// ...
import { SurveyCreatorModule } from 'survey-creator-angular';

@NgModule({
  declarations: [ ... ],
  imports: [
    ...,
    SurveyCreatorModule
  ],
  providers: [ ... ],
  bootstrap: [ ... ]
})
export class AppModule { }

To render Survey Creator, add a <survey-creator> element to your component template and bind the element's model attribute to the model instance you created in the previous step:

<div id="surveyCreator">
  <survey-creator [model]="surveyCreatorModel"></survey-creator>
</div>
#surveyCreator {
    height: 100vh;
    width: 100vw;
}
View Full Code
<!-- survey-creator.component.html -->
<div id="surveyCreator">
  <survey-creator [model]="surveyCreatorModel"></survey-creator>
</div>
// survey-creator.component.ts
import { Component, OnInit } from "@angular/core";
import { SurveyCreatorModel } from "survey-creator-core";

const creatorOptions = {
  showLogicTab: true,
  isAutoSave: true
};

@Component({
  selector: 'survey-creator-component',
  templateUrl: './survey-creator.component.html',
  styleUrls: ['./survey-creator.component.css']
})
export class SurveyCreatorComponent implements OnInit {
  surveyCreatorModel: SurveyCreatorModel;
  ngOnInit() {
    const creator = new SurveyCreatorModel(creatorOptions);
    this.surveyCreatorModel = creator;
  }
}
/* survey-creator.component.css */
#surveyCreator {
    height: 100vh;
    width: 100vw;
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SurveyCreatorModule } from 'survey-creator-angular';

import { AppComponent } from './app.component';
import { SurveyCreatorComponent } from './survey-creator/survey-creator.component';

@NgModule({
  declarations: [
    AppComponent,
    SurveyCreatorComponent
  ],
  imports: [
    BrowserModule,
    SurveyCreatorModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Save and Load Survey Model Schemas

Survey Creator produces survey model schemas as JSON objects. You can persist these objects on your server: save updates and restore previously saved schemas. To save a JSON object, implement the saveSurveyFunc function. It accepts two arguments:

  • saveNo
    An incremental number of the current change. Since web services are asynchronous, you cannot guarantee that the service receives the changes in the same order as the client sends them. For example, change #11 may arrive to the server faster than change #10. In your web service code, update the storage only if you receive changes with a higher saveNo.

  • callback
    A callback function. Call it and pass saveNo as the first argument. Set the second argument to true or false based on whether the server applied or rejected the change.

The following code shows how to use the saveSurveyFunc function to save a survey model schema in a localStorage or in your web service:

// ...
@Component({
  // ...
})
export class SurveyCreatorComponent implements OnInit {
  ngOnInit() {
    // ...
    creator.saveSurveyFunc = (saveNo: number, callback: Function) => { 
      // If you use localStorage:
      window.localStorage.setItem("survey-json", creator.text);
      callback(saveNo, true);

      // If you use a web service:
      saveSurveyJson(
          "https://your-web-service.com/",
          creator.JSON,
          saveNo,
          callback
      );
    };
    // ...
  }
}

// If you use a web service:
function saveSurveyJson(url: string | URL, json: object, saveNo: number, callback: Function) {
  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    },
    body: JSON.stringify(json)
  })
  .then(response => {
    if (response.ok) {
      callback(saveNo, true);
    } else {
      callback(saveNo, false);
    }
  })
  .catch(error => {
    callback(saveNo, false);
  });
}

To load a survey model schema JSON into Survey Creator, assign the schema to Survey Creator's JSON or text property. Use text if the JSON object is converted to a string; otherwise, use JSON. The following code takes a survey model schema from the localStorage. If the schema is not found (for example, when Survey Creator is launched for the first time), a default JSON is used:

const defaultJson = {
  pages: [{
    name: "Name",
    elements: [{
      name: "FirstName",
      title: "Enter your first name:",
      type: "text"
    }, {
      name: "LastName",
      title: "Enter your last name:",
      type: "text"
    }]
  }]
};

// ...
@Component({
  // ...
})
export class SurveyCreatorComponent implements OnInit {
  ngOnInit() {
    // ...
    creator.text = window.localStorage.getItem("survey-json") || JSON.stringify(defaultJson);
    // ...
  }
}
View Full Code
<!-- survey-creator.component.html -->
<div id="surveyCreator">
  <survey-creator [model]="surveyCreatorModel"></survey-creator>
</div>
// survey-creator.component.ts
import { Component, OnInit } from "@angular/core";
import { SurveyCreatorModel } from "survey-creator-core";

const creatorOptions = {
  showLogicTab: true,
  isAutoSave: true
};

const defaultJson = {
  pages: [{
    name: "Name",
    elements: [{
      name: "FirstName",
      title: "Enter your first name:",
      type: "text"
    }, {
      name: "LastName",
      title: "Enter your last name:",
      type: "text"
    }]
  }]
};

@Component({
  selector: 'survey-creator-component',
  templateUrl: './survey-creator.component.html',
  styleUrls: ['./survey-creator.component.css']
})
export class SurveyCreatorComponent implements OnInit {
  surveyCreatorModel: SurveyCreatorModel;
  ngOnInit() {
    const creator = new SurveyCreatorModel(creatorOptions);
    creator.text = window.localStorage.getItem("survey-json") || JSON.stringify(defaultJson);

    creator.saveSurveyFunc = (saveNo: number, callback: Function) => { 
      window.localStorage.setItem("survey-json", creator.text);
      callback(saveNo, true);
      // saveSurveyJson(
      //     "https://your-web-service.com/",
      //     creator.JSON,
      //     saveNo,
      //     callback
      // );
    };
    this.surveyCreatorModel = creator;
  }
}

// function saveSurveyJson(url: string | URL, json: object, saveNo: number, callback: Function) {
//   fetch(url, {
//     method: 'POST',
//     headers: {
//       'Content-Type': 'application/json;charset=UTF-8'
//     },
//     body: JSON.stringify(json)
//   })
//   .then(response => {
//     if (response.ok) {
//       callback(saveNo, true);
//     } else {
//       callback(saveNo, false);
//     }
//   })
//   .catch(error => {
//     callback(saveNo, false);
//   });
// }
/* survey-creator.component.css */
#surveyCreator {
    height: 100vh;
    width: 100vw;
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SurveyCreatorModule } from 'survey-creator-angular';

import { AppComponent } from './app.component';
import { SurveyCreatorComponent } from './survey-creator/survey-creator.component';

@NgModule({
  declarations: [
    AppComponent,
    SurveyCreatorComponent
  ],
  imports: [
    BrowserModule,
    SurveyCreatorModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Manage Image Uploads

When survey authors design a form or questionnaire, they can add images to use as a survey logo or background, in the survey header, or within Image and Image Picker questions. Those images are embedded in the survey and theme JSON schemas as Base64 URLs. However, this technique increases the schema size. To avoid this, you can upload images to a server and save only image links in the JSON schemas.

To implement image upload, handle the onUploadFile event. Its options.files parameter stores the images you should send to your server. Once the server responds with an image link, call the options.callback(status, imageLink) method. Pass "success" as the status parameter and a link to the uploaded image as the imageLink parameter.

// ...
@Component({
  // ...
})
export class SurveyCreatorComponent implements OnInit {
  ngOnInit() {
    // ...
    creator.onUploadFile.add((_, options) => {
      const formData = new FormData();
      options.files.forEach((file: File) => {
        formData.append(file.name, file);
      });
      fetch("https://example.com/uploadFiles", {
        method: "post",
        body: formData
      }).then(response => response.json())
        .then(result => {
          options.callback(
            "success",
            // A link to the uploaded file
            "https://example.com/files?name=" + result[options.files[0].name]
          );
        })
        .catch(error => {
          options.callback('error');
        });
    });
    // ...
  }
}
View Full Code
<!-- survey-creator.component.html -->
<div id="surveyCreator">
  <survey-creator [model]="surveyCreatorModel"></survey-creator>
</div>
// survey-creator.component.ts
import { Component, OnInit } from "@angular/core";
import { SurveyCreatorModel } from "survey-creator-core";

const creatorOptions = {
  showLogicTab: true,
  isAutoSave: true
};

const defaultJson = {
  pages: [{
    name: "Name",
    elements: [{
      name: "FirstName",
      title: "Enter your first name:",
      type: "text"
    }, {
      name: "LastName",
      title: "Enter your last name:",
      type: "text"
    }]
  }]
};

@Component({
  selector: 'survey-creator-component',
  templateUrl: './survey-creator.component.html',
  styleUrls: ['./survey-creator.component.css']
})
export class SurveyCreatorComponent implements OnInit {
  surveyCreatorModel: SurveyCreatorModel;
  ngOnInit() {
    const creator = new SurveyCreatorModel(creatorOptions);
    creator.text = window.localStorage.getItem("survey-json") || JSON.stringify(defaultJson);

    creator.saveSurveyFunc = (saveNo: number, callback: Function) => { 
      window.localStorage.setItem("survey-json", creator.text);
      callback(saveNo, true);
      // saveSurveyJson(
      //     "https://your-web-service.com/",
      //     creator.JSON,
      //     saveNo,
      //     callback
      // );
    };

    // creator.onUploadFile.add((_, options) => {
    //   const formData = new FormData();
    //   options.files.forEach((file: File) => {
    //     formData.append(file.name, file);
    //   });
    //   fetch("https://example.com/uploadFiles", {
    //     method: "post",
    //     body: formData
    //   }).then(response => response.json())
    //     .then(result => {
    //       options.callback(
    //         "success",
    //         // A link to the uploaded file
    //         "https://example.com/files?name=" + result[options.files[0].name]
    //       );
    //     })
    //     .catch(error => {
    //       options.callback('error');
    //     });
    // });

    this.surveyCreatorModel = creator;
  }
}

// function saveSurveyJson(url: string | URL, json: object, saveNo: number, callback: Function) {
//   fetch(url, {
//     method: 'POST',
//     headers: {
//       'Content-Type': 'application/json;charset=UTF-8'
//     },
//     body: JSON.stringify(json)
//   })
//   .then(response => {
//     if (response.ok) {
//       callback(saveNo, true);
//     } else {
//       callback(saveNo, false);
//     }
//   })
//   .catch(error => {
//     callback(saveNo, false);
//   });
// }
/* survey-creator.component.css */
#surveyCreator {
    height: 100vh;
    width: 100vw;
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SurveyCreatorModule } from 'survey-creator-angular';

import { AppComponent } from './app.component';
import { SurveyCreatorComponent } from './survey-creator/survey-creator.component';

@NgModule({
  declarations: [
    AppComponent,
    SurveyCreatorComponent
  ],
  imports: [
    BrowserModule,
    SurveyCreatorModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

View Demo

To view the application, run ng serve in a command line and open http://localhost:4200/ in your browser.

View Full Code on GitHub

Further Reading

Copyright © 2023 Devsoft Baltic OÜ. All rights reserved.

Your cookie settings

We use cookies on our site to make your browsing experience more convenient and personal. In some cases, they are essential to making the site work properly. By clicking "Accept All", you consent to the use of all cookies in accordance with our Terms of Use & Privacy Statement. However, you may visit "Cookie settings" to provide a controlled consent.

Your renewal subscription expires soon.

Since the license is perpetual, you will still have permanent access to the product versions released within the first 12 month of the original purchase date.

If you wish to continue receiving technical support from our Help Desk specialists and maintain access to the latest product updates, make sure to renew your subscription by clicking the "Renew" button below.

Your renewal subscription has expired.

Since the license is perpetual, you will still have permanent access to the product versions released within the first 12 month of the original purchase date.

If you wish to continue receiving technical support from our Help Desk specialists and maintain access to the latest product updates, make sure to renew your subscription by clicking the "Renew" button below.