Mastering Jquery Query Builder within Angular: A Comprehensive Guide

I am exploring how to integrate the jQuery Query Builder into my angular-cli project.

Initially, I attempted to use the plugin from laplasianin/angular-jqueryQueryBuilder, but I struggled with importing it into my component due to lack of clear instructions. My knowledge of angular/typescript is limited.

Subsequently, I tried installing the builder package on my own: npm install jQuery-QueryBuilder

I included it in my component similar to how you would import jQuery. Below is an example code snippet based on this demo:

import {AfterViewInit, Component} from "@angular/core";
import * as jQuery from "jquery";
import "jQuery-QueryBuilder/dist/js/query-builder.standalone.js";
import "jQuery-QueryBuilder/dist/css/query-builder.default.css";

@Component({
    selector: 'app-query-builder',
    templateUrl: './query-builder.component.html',
    styleUrls: ['./query-builder.component.scss']
})
export class QueryBuilderComponent implements AfterViewInit{
    protected rules_basic = {
        condition: 'AND',
        rules: [{
            id: 'price',
            operator: 'less',
            value: 10.25
        }, {
            condition: 'OR',
            rules: [{
                id: 'category',
                operator: 'equal',
                value: 2
            }, {
                id: 'category',
                operator: 'equal',
                value: 1
            }]
        }]
    };

    ngAfterViewInit() {
        this.getQueryBuilder();
    }


    private getQueryBuilder() {
        let queryBuilder = jQuery.fn.queryBuilder;
        jQuery('#builder').queryBuilder({
            plugins: ['bt-tooltip-errors'],

            filters: [{
                id: 'name',
                label: 'Name',
                type: 'string'
            },
                // Other filter configurations omitted for brevity
            ],

            rules: this.rules_basic
        });
    }
}

While the application compiles and loads successfully, I encounter the following error message:

Cannot read property 'template' of undefined
.

I am struggling to troubleshoot and resolve this issue. Any guidance or assistance would be highly appreciated. Thank you.

======= EDIT Providing detailed error information as requested:

ERROR TypeError: Cannot read property 'template' of undefined
    at QueryBuilder.<anonymous> (query-builder.standalone.js:415)
    at Array.forEach ()
    at new QueryBuilder (query-builder.standalone.js:410)
    at jQuery.fn.init.$.fn.queryBuilder (query-builder.standalone.js:3934)
    at QueryBuilderComponent.QueryBuilderComponent.getQueryBuilder (query-builder.component.ts:40)
    at QueryBuilderComponent.QueryBuilderComponent.ngAfterViewInit (query-builder.component.ts:33)
    at callProviderLifecycles (core.es5.js:11269)
    at callElementProvidersLifecycles (core.es5.js:11244)
    at callLifecycleHooksChildrenFirst (core.es5.js:11228)
    at checkAndUpdateView (core.es5.js:12325)

======= EDIT Updated the code to match current implementation practices.

Answer №1

In the first place, laplasianin/angular-jqueryQueryBuilder is a specialized AngularJs (1) library.

Furthermore, to ensure its functionality, you need to add these lines in your angular-cli.json file:

  "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.css",
    "../node_modules/jQuery-QueryBuilder/dist/css/query-builder.default.css",
    "styles.css"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/bootstrap/dist/js/bootstrap.min.js",
    "../node_modules/jQuery-QueryBuilder/dist/js/query-builder.standalone.min.js"        
  ],

Your component code:

import { Component, AfterViewInit } from '@angular/core';

declare var $: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

 protected rules_basic = {
        condition: 'AND',
        rules: [{
            id: 'price',
            operator: 'less',
            value: 10.25
        }, {
            condition: 'OR',
            rules: [{
                id: 'category',
                operator: 'equal',
                value: 2
            }, {
                id: 'category',
                operator: 'equal',
                value: 1
            }]
        }]
    };

    ngAfterViewInit() {
        this.getQueryBuilder();
    }

    private getQueryBuilder() {
        $('#builder').queryBuilder({
            plugins: ['bt-tooltip-errors'],

            filters: [{
                id: 'name',
                label: 'Name',
                type: 'string'
            }, {
                id: 'category',
                label: 'Category',
                type: 'integer',
                input: 'select',
                values: {
                    1: 'Books',
                    2: 'Movies',
                    3: 'Music',
                    4: 'Tools',
                    5: 'Goodies',
                    6: 'Clothes'
                },
                operators: ['equal', 'not_equal', 'in', 'not_in', 'is_null', 'is_not_null']
            }, {
                id: 'in_stock',
                label: 'In stock',
                type: 'integer',
                input: 'radio',
                values: {
                    1: 'Yes',
                    0: 'No'
                },
                operators: ['equal']
            }, {
                id: 'price',
                label: 'Price',
                type: 'double',
                validation: {
                    min: 0,
                    step: 0.01
                }
            }, {
                id: 'id',
                label: 'Identifier',
                type: 'string',
                placeholder: '____-____-____',
                operators: ['equal', 'not_equal'],
                validation: {
                    format: /^.{4}-.{4}-.{4}$/
                }
            }],

            rules: this.rules_basic
        });
    }

}

Remember:

  • Execute npm install bootstrap --save
  • Execute npm install jquery --save
  • Execute npm install jQuery-QueryBuilder --save

Despite lacking autocompletion feature, it functions as intended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issues while attempting to run an npm install command on the package.json file

Having trouble running npm install to set up my Angular project on a Mac. It seems like the issues are due to working with an older project. npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @angular-devkit/< ...

eliminate any following divs that come after a specific child element

I have a similar structure like the following : <div> <div class="productPage"></div> <div>is hidden</div> // ***this content will be hidden </div> // *** this one will not become hidden. <div>n ...

Display the current language in the Vue language dropdown

My component is called DropdownLanguage.vue Goal: I need to show the current active language by default in the :text="selectedOptionDropdown" attribute. For example, it should display "English" which corresponds to languages.name. I'm struggling with ...

How can the reset functionality of a function in an Angular 1.5 component's controller be implemented when transitioning to a different state?

I am facing an issue with my Angular 1.5 component and controller that uses the controllerAs syntax. I have written a function to add an extra css class to the component element if a specific html element exists on the page. However, when switching to a di ...

Error encountered during Next.js project build: Entry point specified for implicit type library 'build'

While working on my nextjs project, I encountered the following error: Type error: Cannot find type definition file for 'build'. The file is in the program because: Entry point for implicit type library 'build' Can someone guide ...

A specialized authorization attribute that combines the name of the controller with the name of the action

My custom AuthorizeAttribute is functioning well, as shown in this post about handling session timeout in ajax calls. However, there is a challenge with the LogOn Action of the Account Controller in ASP.NET MVC. Upon logging on, it returns to the last page ...

Utilizing React with Typescript to create JSX text translation files

My task involves translating text stored in a file... ///translations.txt const TEXT: { [x: string]: { [y: string]: string } } = { en: { joinNow: <React.Fragment>Join <b>Now<b/></React.Fragment>, signUp: <React.Fragmen ...

Adjusting the background color of an HTML element with CSS through the power of Javascript

I am looking to dynamically change the background color of an element in CSS using JavaScript when a button is clicked. Currently, my CSS code looks like this: div.box { width:100px; height:100px; background-color:#FF2400; } I want the backg ...

What are the best practices for presenting Motion JPEG binary data streams using Angular, Ionic, and JavaScript?

I am developing an application for a device that will receive a POST request and send back a binary data stream in the format of multipart/x-mixed-replace. My goal is to display this stream on a specific section of my app's homepage. After conducting ...

Numerous instances of running JavaScript code

Having an issue with a JavaScript script. Using AJAX to load a subpage and append code to a div. $.ajax ({ type: "POST", url: "load/page/", dataType: "json", success : function(data) { $('.content').empty(); ...

methods for transforming JSON array output objects into individual non-array values

I'm facing an issue with a JSON result that contains latitude and longitude as an array like [13.0801721, 80.2838331]. I need help in converting this to comma-separated values without the array brackets, similar to 13.0801721, 80.2838331. This is my ...

Cause the production build to fail while maintaining successful builds in development mode

I am in the process of developing an Angular application and have a question regarding ensuring the build fails in production but not during local development. Specifically, I have a complex login logic that I would like to bypass while working on it. To ...

Receive alerts from flash document within html

I have a flash file embedded in an html document using the embed tag. I am looking for a way to trigger a JavaScript action, such as an alert, once the Flash content has finished playing. Is there a method to achieve this? ...

Is there potential for this to result in a security vulnerability?

I have a MongoDB collection called "users" where I need to include a new field "wallet_amount" when users add money to their wallet. Currently, during user registration, I am attempting to insert a document like this: db.users.insert( { email: "<a href ...

Typescript: The function parameter in a class method is more specific than in the superclass

I am facing an issue with two TypeScript classes where one extends the other: type NamedObject = { name: string; } class AnyObjectManager { objectList = []; getAnyObject = (matches: (o: object) => boolean) => { for (const o of t ...

What is the best way to extract this function from the methods section of this Vue component?

I recently came across this Vue component called BarChart.vue on https://github.com/apexcharts/vue3-apexcharts Here is the script section of the component; <script> /* eslint-disable */ export default { name: "BarExample", data: funct ...

Weather Application featuring Circular Slider

I've been on the hunt for a circular slider animation. Imagine it working like this: <input type="range" min="0" max="50" value="0" step="5" onchange="showValue(this.value)" /> <span id="range">0</span> function showValue(newValue ...

Unable to get the jQuery click event handler to function properly

I am currently working on an asp.net web application in VS 2013. The application utilizes nested master pages, with the main master page containing the following code snippet: <!DOCTYPE html> <script src="http://code.jquery.com/jquery-lat ...

Using Angular service worker to pre-fetch video files

Issue arises when the service worker prefetches the entire video embedded on the page, leading to performance problems. My ngsw-config.json only contains configurations for local files, whereas the video is located on a different subdomain under /sites/def ...

Error encountered when accessing the next sibling of the current element ($(this))

Wondering why I can only see the save button when clicking edit and not the cancel button. Here is my code snippet: $(".editlink").on("click", function(e){ e.preventDefault(); var dataset = $(this).prev(".datainfo"); var savebtn = $(this) ...