ngSurvey
  • ✔️ What is ngSurvey ?
  • ❔Help on Help
  • 📁Projects
    • Creating a New Survey
    • Folders
      • Project Trashcan
    • Survey Information
    • Survey Search
    • Collaboration
    • Import / Export
      • JSON Survey Export / Import
      • XLSForm
        • Survey Sheet
          • Types
          • Groups
          • Appearances
          • Relevant
          • Constraint
          • Calculations
          • Multi-Languages
          • Choice filters (Casacade)
        • Choices Sheet
        • Settings Sheet
        • XLSForm Samples
  • 📄Forms / Surveys
    • Overview Dashboard
      • Dashboard Title
      • Dashboard Information Box
      • Dashboard Reports
      • Last Respondents
      • Last Sentiments
    • Form Designer
      • Questions
        • Creating a Question
        • Editing a Question
          • Question Preset Styles
        • Question Properties
          • Conversation reply type
            • Auto reply type
          • Question Branching
          • Skip / Hide Logic
        • Question Types
          • Standard
            • Single Choice
            • Multiple Choice
            • Image Choices
            • Dropdown List
            • Autocomplete
            • Text / Comment Field
          • Matrix Questions
            • Columns / Rows Sums
            • Single Matrix
            • Multi Matrix
            • Mobile Rendering
          • Satisfaction Questions
            • Net Promoter Score® Question
              • Understanding the Net Promoter Score® (NPS)
            • CSAT Score
              • Understating CSAT Score
            • CES Score
              • Understanding CES
            • Star Rating
            • Smileys
            • Thumbs Up / Down
          • Choice-Based Conjoint (CBC)
            • Create a Conjoint Question
            • Design Experiments
              • Balanced Design
              • Manual Design
              • Import Design
            • Reporting / Export
          • Advanced Types
            • Appointment Calendar
            • Constant Sum
            • Answer Ranking
            • Slider Scale
            • File Upload
            • Hidden Question
            • Contact Details
          • Questions Generator
          • Smart Generator
        • Question Blocks
        • Static / Images Content
        • Rating
        • Panel Linking
          • Panel Auto Filling
          • Panel Updating
      • Answers
        • Adding an Answer
        • Editing an Answer
        • Answer Properties
          • Field Properties
          • Reporting / Exports
          • Skip / Hide Logic
          • Entry Validation
        • Answer Types
          • Creating New Type
            • Custom Validation Code
            • Lists
              • JSON / REST API Lists
              • SQL Server Lists
                • Parent / Child Related Lists
                • SQL Parameters
              • List Items
            • Widgets
              • Widget Samples
                • Widget Definitions
                • Basic Field
                • Multiple input type
                • Basic Selection
                • Material Date
                • Material selection
                • Total Score Per Page
          • Selection Answers
            • Checkbox
            • Radio Button
          • Other selection
          • Entry Field
          • Password
          • Captcha
          • Calendar Date
          • Calendar time
          • Compare Field
          • Countries
          • Email
          • Email Validator
          • Hidden Field
          • File Upload
          • Language Selector
          • Phone Confirmation
          • Signature Pad
          • Slider
          • Constant sum
          • Constant sum total
          • Ranking Field
          • Ranking drag / drop
          • Text label
          • Time Picker
          • Appointment Calendar
      • Pages
        • Page Branching
        • Skip / Hide Logic
        • Conditional Redirection
        • Thanks / End Page
          • Redirection URL
          • Conditional Thanks Message
        • Page Looping
          • Looping Pipes
        • Pages Navigator
      • Multi-Language Forms
        • Setup multi-languages
        • Import / Export
        • Auto-translation
        • Resources
      • Survey Properties
        • Progress Completion
          • Respondent Answers Update
        • Single Question Flow
          • Flow Animation Transitions
        • Privacy
          • Privacy checklist
        • Quotas
        • Kiosk
        • Form Code
        • Survey Security
      • Footer Manager
      • Repeatable Sections
      • Rich Text Editor
        • Rich Attributes
      • Piping
        • Text / Data Piping
        • Carry Forward Answers
      • Preview / Testing
        • Pref-filled answers
      • Form Trashcan
      • Scoring
      • Timer
      • Conditions
        • Condition Groups
        • Conditions Rules
          • Question Conditions
          • Javascript Conditions
      • Geolocation
        • Browser Location
        • IP Address Location
        • Location Reporting
      • Google Analytics
        • Google Analytics Events
    • Flow Logic Graph
      • Page Branching Graph
      • Question Branching Graph
    • Security
      • Security Items
        • Active Directory Security
        • Azure Active Directory Security
        • Auth0 Security
        • Captcha
        • CAS Authentication
        • HTTP Function
          • Azure Function Login Sample
        • Invitation Code
        • IP Protection
        • IP Access Control
        • Local Users Security
        • OpenId Connect
        • Panel Security
          • Panelist Mapping
        • Password
        • Quota Restrictions
        • Tokens
          • Token Generator
            • Individual Entry
            • Automatic Generator
            • CSV File
          • Token Manager
          • Token and Querystring
          • Token Hierarchy / Permissions
        • Referer
        • SQL Security
      • Key Provider
      • Data Attributes
    • Style / Branding
      • Style Library
      • Style Editor
        • Style
          • Header / Footer
          • Header Logo Image
        • Theme
        • Elements
        • CSS
          • CSS Classes
          • CSS Rating Sample
        • Mobile / Responsive Design
        • Custom Font
      • Media Gallery
    • Tasks
      • Task Items
        • Completion Alerts
        • Google Sheet Task
        • SQL Query Task
        • Webhooks
          • Webhooks payload transform
      • Triggers
    • Publish
      • Web Link
      • Offline Survey
        • Uploading respondents
      • Embed Form
      • QR Code
      • Word Format Export
      • Website Intercepts
        • How to implement intercepts
        • Intercept Hosts
        • Intercepts
          • Intercept Properties
          • Intercept Layout
          • Intercept Triggers
          • Multi-Language Intercepts
          • Intercept Display Formats
      • Page
    • Campaigns
      • Information Box
      • Campaign
        • Email Distribution
          • Email List
          • Import Emails
        • Panel Members Distribution
        • Mobile Phone Distribution
          • SMS Distribution
          • WhatsApp Distribution
            • WhatsApp Invitations
            • WhatsApp Conversation
          • Phone Number List
          • Import Phones
        • Invitation Message
          • Invitation Piping Tags
          • Embedding a Question
          • WhatsApp Template
        • Reminders
          • One time reminders
        • Schedules
        • Virtual Campaign
        • Campaign Results
      • Campaign Batches
      • Invitation Templates
      • REST Trigger
    • Respondents
      • Respondent Details
      • Editing Respondent Answers
      • Respondents Status
      • Archived Respondents
      • Actions Links
    • Reporting
      • Default Report
      • Report Builder
        • Report Items
          • Bar Chart
          • Pie Chart
          • Free Text Report
          • Sentiment Index
          • Net Promoter Score®
          • Historical Trends Chart
          • Cross Tabulation
          • Tag Clouds
          • T.U.R.F
          • Ranking Report
          • Constant Sum Report
          • Languages Chart
          • Location Chart
      • Text Reports
        • Sentiment Analysis
      • Report Filters
      • Test Data Generator
      • Historical Trends
      • Files Vault
      • Multi-Language Report
      • Reporting Printing
    • Data Exports / Imports
      • Data Exports
        • Export Jobs
        • CSV / Excel
          • Excel
          • CSV Individual Answers
          • CSV Separated Selection / Fields
          • Questions as Rows
        • SPSS / SAV
        • JSON
        • Aggregated Results
        • Word Respondents
        • Export Templates
      • Data Imports
      • Variables
    • Data Access
    • Activity Log
  • 💬Conversational Surveys
    • Get Conversation Started
    • Conversation Questions
      • Answer Reply
      • Text Reply
      • File Upload
      • NPS
      • CSAT
      • CES
      • Language Reply
    • Conversation Commands
    • WhatsApp Conversations
    • Unifonic Template Message
  • 📖Shared Sessions Surveys
    • Sessions
  • ✨AI Suite
    • AI Generated Survey
    • Smart Questions Generator
    • Smart Answers Suggestions
    • Smart Analysis
    • Smart Columns
      • Smart Columns Properties
      • Smart Works
        • Custom Prompt
        • Translation
        • NPS
        • Sentiment
        • Labels
  • 👪Panels
    • Panel Connectors
      • Built-in Connector
        • Import panelist from CSV
      • Database Connector
    • Panel information
    • Panelists
    • Panel Views
    • Panel Attributes
    • Entry Approvals
    • Panelist Surveys
    • Panel Properties
  • 👤Personal Account
    • Account Settings
    • Developer
      • API Connection Sample
        • Get Survey From API
      • Power Apps / Logic App Flow Integration
        • Connector Setup
        • Connector / Mail Example
      • Zapier.com Connection
  • 🔐Access Control
    • Users
    • Groups
    • Roles
      • Rights
  • 🔑Data Encryption
    • Encryption Setup
      • Transparent Encryption
        • Azure Encryption Setup
        • IIS Encryption Setup
      • PGP Encryption
    • Data Classification
      • Internal
      • Sensitive
      • Restricted
    • Respondent Answers Encryption
    • File Upload Encryption
    • Campaign Encryption
  • 🕸️ Tenants
  • 🚀On-Site Setup
    • Enterprise Edition Installation
      • Docker
        • Filesystem Storage
      • Microsoft Azure
      • Amazon Web Services
        • AWS Elastic Beanstalk
          • AWS EBS / STAND ALONE SQL SERVER
          • AWS EBS / SQL Server
        • Cognito
        • LightSail
      • Microsoft IIS
        • Azure KeyVault
        • Update / Upgrade
      • ZIP Archive
      • Linux (Ubuntu / CentOS)
        • Linux SSL
      • Database Backend
        • Microsoft SQL Server
        • Oracle MySQL
        • MariaDB
        • PostgreSQL
      • WhatsApp Messenging
        • Twilio
        • Unifonic
      • Cluster / Scale out setup
      • Microsoft Entra / Azure AD
        • Entra Setup
        • Register Entra Users
      • Active Directory
        • Active Directory Setup
        • Register Active Directory Users
      • Environment Variable Settings
      • Content Security Policy (CSP)
      • Cross Origins Setup (CORS)
    • System Settings
      • General
      • Mailing Server
        • SMTP Mailing Server
        • IIS SMTP / Exchange Server
        • Postmark
        • Twilio / Sendgrid
        • MailJet
      • Account Security
      • Connections vault
      • AI Suite Provider
        • OpenAI
        • Azure AI
      • Third Party APIs
        • Microsoft
        • IPStack
      • Google
        • Captcha Setup
        • Google Web Font
        • Service Account
      • Azure Entra Settings
      • Active Directory Settings
      • OpenId Connect Settings
      • Mobile Messenging
        • Twilio
        • HTTP SMS Messenging
        • Amazon SNS
        • Unifonic
      • Translations
      • File Storage
      • Bounce Account
    • White-Label
    • Register Trial Copy
    • Upgrades
    • Release Notes
    • Change log
  • 📚Walkthroughs
    • Quick create survey start
    • Translate a survey
    • Rename a survey
    • Restore a deleted survey
    • Invite respondents to a survey
    • Capture value from query string
    • Share a survey with other users
    • Using token in email campaigns
    • Using a campaign with MailChimp
    • Power BI Integration
      • Link data to Power BI
      • Reporting with Power BI
    • Tableau Integration
      • Link data to Tableau
        • Reporting with Tableau
    • Link existing SQL table to a survey
    • Send invitations using an existing SQL Table
    • Export data to Excel
    • Export data to R
    • Zendesk integration
  • ©️ Copyrights / EULA
    • License
    • Copyrights and disclaimers
Powered by GitBook

(c) 2024 Data Illusion Zumbrunn. All rights reserved. Reproduction strictly forbidden.

On this page

Was this helpful?

  1. Forms / Surveys
  2. Form Designer
  3. Answers
  4. Answer Types
  5. Creating New Type
  6. Widgets
  7. Widget Samples

Widget Definitions

In this page you will find all the definitions of the parent class from which childs can inherit to become an ngSurvey widget.

class NGSWidget {
  static get type() {
    return "NGSWidget"
  }

  /* Html template that will generate before class gets created
     All id's and css classes name will be suffixed by the uniqueId
     provided during creation of the widget */
  static get template() {}

  /* Html template is used during design time of the form
     If null the actual widget template will be rendered */
  static get designTimeTemplate() {}

  /* Html template is when form is shown to be printed */
  static get printTemplate() {}

  /* Inline css style that will be added to the page
     note that style classes names will be scoped
     to the widget unique id 
  */
  static get style() {}

  /* Inline javascript code that will be added to 
     the page as long as the widget */
  static get script() {}

  static get selectionWidget() {
    return true;
  }

  /* Does this widget support label, the label is the text a form
  admin can enter using the form design and which will be displayed
  before the widget template */
  static get hasLabel() {
    return true;
  }

  /* Displays the ngsurvey native error message box 
     under the control
  */
  static get displayErrorMessage() {
    return true;
  }

  /* Will prefix all CSS classes from the widget style
     with a unique value to avoid conflicts if other components 
     have registered these classes under the same name.
     Note that it wont parse external CSS dependencies.
     0 : No encapsulation
     1 : Shadow CSS - native ngSurvey prefix processor
  */
  static get encapsulationMode() {
    return 1;
  }

  /* Allows the answer to be set required or not
   from the answer settings page to make
   the widget answer required during survey
  */
  static get required() {
    return false;
  }

  /* Properties that can be set in from the form designer for each
   answer using this widget as an answer type in the answer settings */
  static get propertiesDef() {}

  /* External javascript code dependencies that will be loaded
   before the widget gets created */
  static get jsDependencies() {}

  /* External css code dependencies that will be loaded
   before the widget gets created */
  static get cssDependencies() {}

  /*
    setAnswer; // callback furnction to post a value from the widget eg: answerPosted(widgetAnswerValue)
    valueChanges$; // Observable that returns the value of the widget
      containerElement;
      labelElement;
      respondentAnswers = [];
      uniqueId;
      answerContext;
      formContext;
      sectionIndex;
      properties;
      initialValue;
      label;
    */

  /* containerElement : DOM element holding the template
     labelElement: DOM element holding the label
     answerContext: Answer context that provides helper methods to interact with the answer
     formContext: Form context that provides helper methods to interact with the form
     uniqueId: must be used to query as suffix the template element id's or css classes
     properties : instance specific property values
     setAnswer: function that will set the given text value of the widget setAnswer(textVal) 
     valueChanges: monitor any value changes of the widget
     */
  constructor(containerElement, labelElement, answerContext, formContext,
    sectionIndex, uniqueId, properties, setAnswerCallback, valueChanges$) {
    this._value = null;
    this._subscribers = [];
    this.containerElement = containerElement;
    this.labelElement = labelElement;
    this.uniqueId = uniqueId;
    this.formContext = formContext;
    this.sectionIndex = sectionIndex;
    this.properties = properties;
    this.answerContext = answerContext;
    this.initialValue = answerContext.initialValue;
    this.valueChanges$ = valueChanges$;
    this.setAnswer = (value) => {
      // Keeps a local copy of the value being set
      this._value = value;

      setAnswerCallback(value);
    };

    this.getLabel$(label => {
      this.label = label;
    })

    this.getRespondentAnswers$(respondentAnswers => {
      this.respondentAnswers = respondentAnswers;
    });

    this.getAnswers$(answers => {
      this.answers = answers;
    });

    this.getQuestions$(questions => {
      this.questions = questions;
    });

  }

  /* Widget has been template has not yet been added to the DOM
     but its properties have been already been set 
  */
  build() {}

  /* Widget has been template has added to the DOM
     and its properties have been set 
  */
  init() {}

  /* Subscribe to the observable and keeps
     a reference to automatically unsubscribe
     it when the widget gets disposed
  */
  safeSubscribe(obs, next, error, complete) {
    // add to array
    if (obs) {
      this._subscribers.push(obs.subscribe(next, error, complete));
    }
  }

  // Beta Not for production
  remoteValidate() {
    var validationParams = [];
    for (var key in this.properties) {
      validationParams.push(this.getValidationParam(key, this.properties[key]));
    }
    validationParams.push(this.getValidationParam('secret', '6LeFY6QUAAAAAEwJvr1FYG16rVQpJJ1RQEGV19QM'));
    validationParams.push(this.getValidationParam('response', this._value));
    var remoteValidationParams = {
      validationParams
    }
    return this.formContext.answerService.validate(this.answerContext.answer.id, remoteValidationParams).subscribe(val => {
      console.log('validate')
    });
  }

  // Beta  Not for production
  remoteValidateProd() {
    var validationParams = [];
    validationParams.push(this.getValidationParam('secret', '6LeFY6QUAAAAAEwJvr1FYG16rVQpJJ1RQEGV19QM'));
    validationParams.push(this.getValidationParam('response', this._value));
    var remoteValidationParams = {
      validationParams
    }
    return this.formContext.answerService.validate(this.answerContext.answer.id, remoteValidationParams).subscribe(val => {
      console.log('validate')
    });
  }

  getValidationParam(name, value) {
    return {
      name,
      value
    }
  }

  /* 
    returns the properties of the widget 
    in the callback
  */
  getProperties$(propsCallback) {
    this.safeSubscribe(this.answerContext.propertie$, propsCallback, null, null)
  }

  getLabel$(labelCallback) {
    this.safeSubscribe(this.answerContext.label$, labelCallback, null, null)
  }

  getValue$(valueCallback) {
    this.safeSubscribe(this.valueChanges$, (value) => {
      // Callback only if value has changed
      if (value != this._value) {
        valueCallback(value);
      }
    }, null, null)
  }

  isDisabled$(stateCallback) {
    this.safeSubscribe(this.answerContext.disabled$, stateCallback, null, null)
  }

  isSelected$(selectionCallback) {
    this.safeSubscribe(this.answerContext.isSelected$, selectionCallback, null, null)
  }

  getRenderMode$(renderModeCallback) {
    this.safeSubscribe(this.answerContext.renderMode$, renderModeCallback, null, null)
  }

  getLanguage$(languageCallback) {
    this.safeSubscribe(this.formContext.language$, languageCallback, null, null)
  }

  getRespondentAnswers$(respondentAnswersCallBack) {
    this.safeSubscribe(this.formContext.respondentAnswers$, respondentAnswersCallBack, null, null)
  }

  getAnswers$(answersCallBack) {
    this.safeSubscribe(this.formContext.answers$, answersCallBack, null, null)
  }

  getQuestions$(questionsCallBack) {
    this.safeSubscribe(this.formContext.questions$, questionsCallBack, null, null)
  }

  /* Will be called by the form to see if the value is valid
     If not valid must return '' (no error message shown) or the error message to show
     If its valid return null */
  isValid() {
    return null;
  }

  /* Returns the html element from the dom that has been generated 
     from the widget template will match the suffixed ids of the 
     widget template
  */
  getWidgetElementById(id) {
    return this.widgetQuerySelector('#' + id);
  }

  /*
    Queryselector only on the container of the widget.
    Adds the widget unique id to ids (#) to match to 
    the suffixed local ids of the widget template 
  */
  widgetQuerySelector(selector) {
    // Suffix the id with the widget unique id 
    if (selector.indexOf('#') >= 0) {
      selector += this.uniqueId;
    }
    return this.containerElement.querySelector(selector);
  }

  /*
    QueryselectorAll only on the container of the widget.
    Adds the widget unique id to ids (#) to match to 
    the suffixed local ids of the widget template 
  */
  widgetQuerySelectorAll(selector) {
    // Suffix the id with the widget unique id 
    if (selector.indexOf('#') >= 0) {
      selector += this.uniqueId;
    }
    return this.containerElement.querySelectorAll(selector);
  }


  /* Cleans up all things that needs to be cleaned
     up before the widget gets destroyed from the dom */
  dispose() {}

  _disposeSubscribers() {
    if (this._subscribers) {
      this._subscribers.forEach(subscriber => {
        if (subscriber) {
          subscriber.unsubscribe();
        }
      })
      this._subscribers = [];
    }
  }

  /* Hooks the widget events to keep their 
    state in sync */
  _hookEvents() {}

  /* Internal method should not be overriden */
  _dispose() {
    this._disposeSubscribers();
    this.dispose();
  }

  /*  _value;
    _subscribers = [];*/
}

class NGSSelectionWidget extends NGSWidget {
  static get type() {
    return "NGSSelectionWidget"
  }
  /* containerElement : DOM element holding the template
     labelElement: DOM element holding the label
     answerContext: Answer context that provides helper methods to interact with the answer
     formContext: Form context that provides helper methods to interact with the form
     uniqueId: must be used to query as suffix the template element id's or css classes
     selectionId: is the unique id of the group of selection
     selectAnswerCallback: function that will be called when an answer must be selected from widget
     selected$: observable that returns true / false when answer is selected or unselected
     properties : instance specific property values
     setAnswer: function that will set the given text value of the widget setAnswer(textVal) */
  constructor(containerElement, labelElement, answerContext, formContext,
    sectionIndex, uniqueId, selectionId, selected, selectedAnswerCallback,
    selected$, properties, setAnswerCallback, valueChanges$) {
    super(containerElement, labelElement, answerContext,
      formContext, sectionIndex, uniqueId, properties, setAnswerCallback, valueChanges$)

    this.selectionId = selectionId;
    this.isSelected = selected;
    this.selected$ = selected$;

    this.selectAnswer = (selected) => {
      // If its a text answers save value locally  (eg: for "other" answers with fields and selections)
      if ((selected !== false && selected !== true) || selected == null || selected.length == 0) {
        this._value = selected;
      }
      selectedAnswerCallback(selected);
    };

    this.isSelected$(selected => {
      this.isSelected = selected;
    });
  }

  isSelected$(selectionCallback) {
    this.safeSubscribe(this.selected$, selectionCallback, null, null)
  }
}
export class AnswerContext {
  constructor(
    // Answer that is linked to that widget
    private answer: Answer,
    // Custom user defined properties that have been set for this widget  
    private propertie$: Observable<any>,
    // Current rendering mode of the widget eg: DesignTime (design), Standard (running)
    private renderMode$: BehaviorSubject<ControlRenderMode>,
    // Should the widget be disabled ?
    private disabled$: BehaviorSubject<boolean>,
    // Is the label enabled
    private showLabel: boolean,
    // Angular form control holding the value of the a
    private formControl: FormControl,
    // Inital value of the answer, could be the default value set 
    // by the survey admin or the previous respondent answer if the survey
    // is being resumed by the respondent
    private initialValue: string,
    // Label text of the answer, observable will stream the new value
    // if value changes in multi languages survey
    private label$: Observable<string>) { }
}
export class FormContext {
  constructor(
    // Actual respondent of the survey
    private respondent$: Observable<Respondent>,
    // Actual respondent answers of the survey, observable 
    // will stream any new answer update in realtime
    private respondentAnswers$: Observable<RespondentAnswer[]>,    
    // Survey answers
    private answers$: Observable<Answer[]>,
    // Survey questions
    private questions$: Observable<Question[]>,
    // Actual respondent language in multilanguage surveys
    private language$: Observable<Language>,
    // Helper method to access the angular http client
    private httpClient: HttpClient,
    // internal ngSurvey answer http services
    private answerService: AnswerService) { }
}
PreviousWidget SamplesNextBasic Field

Last updated 4 years ago

Was this helpful?

📄