jQWidgets Forums

jQuery UI Widgets Forums Angular angular jqxGrid

This topic contains 9 replies, has 2 voices, and was last updated by  Ivo Zhulev 7 years, 3 months ago.

Viewing 10 posts - 1 through 10 (of 10 total)
  • Author
  • angular jqxGrid #98170

    douglas168
    Participant

    Hi all,

    I am doing my first Angular project with JqxGrid. From Jqxwidgets web site, it basically shows just write all logic in component.ts (such as below)

    import { Component } from '@angular/core';
    
    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html'
    })
    
    export class AppComponent {
        source: any =
        {
            datatype: 'json',
            datafields: [
                { name: 'name', type: 'string' },
                { name: 'type', type: 'string' },
                { name: 'calories', type: 'int' },
                { name: 'totalfat', type: 'string' },
                { name: 'protein', type: 'string' }
            ],
            id: 'id',
            url: '../sampledata/beverages.txt'
        };
    
        dataAdapter: any = new jqx.dataAdapter(this.source);
    
        columns: any[] =
        [
            { text: 'Name', datafield: 'name', width: 250 },
            { text: 'Beverage Type', datafield: 'type', width: 250 },
            { text: 'Calories', datafield: 'calories', width: 180 },
            { text: 'Total Fat', datafield: 'totalfat', width: 120 },
            { text: 'Protein', datafield: 'protein', minwidth: 120 }
        ];
    } 

    and in html just write

    <jqxGrid 
          [width]="850" [source]="dataAdapter" [columns]="columns" [columnsresize]="true">
    </jqxGrid>

    Yet, most I have seen Angular projects uses service.ts such as below

    import { Injectable } from '@angular/core';
    import { User } from "./user";
    import { Http, Response } from "@angular/http";
    import 'rxjs/add/operator/map'
    import 'rxjs/add/operator/catch';
    import { Observable } from "rxjs/Observable";
     
    @Injectable()
    export class UserService {
     
      private apiUrl = 'http://localhost:8080/users';
     
      constructor(private http: Http) {
      }
     
      findAll(): Observable<User[]>  {
        return this.http.get(this.apiUrl)
          .map((res:Response) => res.json())
          .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
      }
     
      findById(id: number): Observable<User> {
        return null;
      }
     
      saveUser(user: User): Observable<User> {
        return null;
      }
     
      deleteUserById(id: number): Observable<boolean> {
        return null;
      }
     
      updateUser(user: User): Observable<User> {
        return null;
      }
     
    }

    and component.ts such as below

    export class UserListComponent implements OnInit {
     
      private users: User[];
     
      constructor(private userService: UserService) { }
     
      ngOnInit() { //when component loading get all users and set the users[]
        this.getAllUsers();
      }
     
      getAllUsers() {
        this.userService.findAll().subscribe(
          users => {
            this.users = users;
          },
          err => {
            console.log(err);
          }
     
        );
      }
     
    }

    and html uses table such as below

    <table class="table">
              <thead>
              <tr>
                <th>#</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>email</th>
                <th></th>
              </tr>
              </thead>
              <tbody>
              <tr *ngFor="let user of users">
                <th scope="row">{{user.id}}</th>
                <td>{{user.firstName}}</td>
                <td>{{user.lastName}}</td>
                <td>{{user.email}}</td>
                <td>
                </td>
              </tr>
     
              </tbody>
            </table>

    Can Jqxgrid be implemented like other angular table?

    Appreciate the help!

    angular jqxGrid #98173

    douglas168
    Participant

    Hi all,

    I found a question on the forum asking pretty similar question (I think).

    https://www.jqwidgets.com/community/topic/angular-4-httpclient-and-jqxgrid/

    Sorry I am new to this and not sure what Ivo meant. Any sample code?

    Appreciate the help!

    angular jqxGrid #98178

    Ivo Zhulev
    Participant

    Hi douglas168,

    The example you’ve given is pure logic and just bind 2-3 props to the UI.
    Angular services are for that yes-> writing logic NOT UI things.
    But there’s a huge difference between the example you’ve shared and our widgets.
    Our widgets are UI components, so you can’t put them inside a service.
    The most you can do is take the data they need through a service.

    Best Regards,
    Ivo

    jQWidgets Team
    http://www.jqwidgets.com/

    angular jqxGrid #98294

    douglas168
    Participant

    Hi Ivo,

    Thank you for the input. Yes, I am trying to get jqxGrid data through Angular service but not sure how? Any example on JqWidget web site?

    Thanks,
    Douglas

    angular jqxGrid #98351

    Ivo Zhulev
    Participant

    Hi douglas168,

    Make the service as a separate file. In the file where your jqxGrid is, subscribe to that service. In the success callback of the subscribe, take the data you received and do the normal things for a jqxGridto initialize(give the data to the dataAdapter…).

    Best Regards,
    Ivo

    jQWidgets Team
    http://www.jqwidgets.com/

    angular jqxGrid #98417

    douglas168
    Participant

    Hi Ivo,

    Thank you for the information. I have the following files and I can’t give the data to the dataAdapter (grid shows up blank) . Please help!

    ArticleService.ts

    import { Injectable } from '@angular/core';
    import {HttpClient, HttpHeaders} from "@angular/common/http";
    
    const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };
    
    @Injectable()
    export class ArticleService {
        //URL for CRUD operations
        private readonly API_URL = "http://localhost:3000/articles";
    
        //Create constructor to get Http instance
        constructor(private http: HttpClient) {
        }
    
        getAllArticles(){
            return this.http.get(this.API_URL);
        }
    }

    jqxgrid.component.ts

    import {Component, OnInit} from '@angular/core';
    import {HttpClient, HttpErrorResponse} from "@angular/common/http";
    import {ArticleService} from "../shared/services/article.service";
    
    @Component({
        selector: 'app-jqxgrid',
        templateUrl: './jqxgrid.component.html',
        styleUrls: ['./jqxgrid.component.scss']
    })
    export class JqxgridComponent implements OnInit {
    
        public articles;
    
        constructor(private http:HttpClient, private articleService: ArticleService) {
        }
    
        ngOnInit(): void {
            this.getAllArticles();
        }
    
        getAllArticles(){
            this.articleService.getAllArticles().retry(3).subscribe(
                data => {this.articles = data},
                (err: HttpErrorResponse) => {
                    if (err.error instanceof Error) {
                        //A client-side or network error occurred.
                        console.log('An error occurred:', err.error.message);
                    } else {
                        //Backend returns unsuccessful response codes such as 404, 500 etc.
                        console.log('Backend returned status code: ', err.status);
                        console.log('Response body:', err.error);
                    }
                },
                () =>console.log('done loading')
    
            );
    
        }
    
        source: any =
            {
                datatype: 'json',
                datafields: [
                    {name: 'id', type: 'int'},
                    {name: 'title', type: 'service'},
                    {name: 'category', type: 'service'}
                ],
                id: 'id',
                url: 'http://localhost:3000/articles'
            };
    
        dataAdapter: any = new jqx.dataAdapter(this.source);
    
        cellsrenderer = (row: number, columnfield: string, value: string | number, defaulthtml: string, columnproperties: any, rowdata: any): string => {
            if (value < 20) {
                return <code><span style='margin: 4px; float:${columnproperties.cellsalign}; color: #ff0000;'>${value}</span></code>;
            }
            else {
                return <code><span style='margin: 4px; float:${columnproperties.cellsalign}; color: #008000;'>${value}</span></code>;
            }
        };
    
        columns: any[] =
            [
                {text: 'Id', datafield: 'id', width: 100},
                {
                    text: 'Title',
                    // columngroup: 'ToDoList',
                    datafield: 'title',
                    cellsalign: 'left',
                    align: 'left',
                    width: 150
                },
                {text: 'Category', datafield: 'category', align: 'center', width: 100}
            ];
    }
    angular jqxGrid #98418

    douglas168
    Participant

    Hi Ivo,

    I can get the following ‘table’ way to display but can’t get ‘jqxgrid’ way to display. I like to keep using jqxgrid with Angular if possible.

    jqxgrid.component.html

    <div class="table-responsive">
                                <table class="table">
                                    <thead>
                                    <tr>
                                        <th> Id</th>
                                        <th>Title</th>
                                        <th>Category</th>
                                        <th></th>
                                        <th></th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <tr *ngFor="let article of articles">
                                        <td>{{article.id}}</td>
                                        <td>{{article.title}}</td>
                                        <td>{{article.category}}</td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
    angular jqxGrid #98423

    Ivo Zhulev
    Participant

    Hi douglas168,

    First of all, do you receive data in the subscribe success callback?
    If yes then there you must do the following:

    
    this.source.localdata = data;
    this.dataAdapter.dataBind();
    this.myGrid.updatebounddata();
    

    Best Regards,
    Ivo

    jQWidgets Team
    http://www.jqwidgets.com/

    angular jqxGrid #98438

    douglas168
    Participant

    Hi Ivo,

    I have two components. Both use the same article.service.ts. One component uses regular table (see articles.components.ts and articles.component.html). However, the other components uses jqxgrid (see jqxgrid.component.ts and jqxgrid.component.html) CAN NOT display data from article.service.ts. If I set ‘localdata: this.datatest’ where datatest is defined within the component, I can get the datatest to display. So, I guess I need help in HOW DO I GET DATA FROM SUBSCRIBE SERVICE TO DISPLAY IN JQXGIRD? Please help!

    (ps. I tried ‘this.source.localdata = data;’ but get Module parse failed: Unexpected token)

    articles.components.ts

    export class ArticlesComponent implements OnInit {
    
        public articles;
    
        // Inject HttpClient into your component or service.
        constructor(private http: HttpClient, private articleService: ArticleService) {
        }
    
        ngOnInit(): void {
            this.getAllArticles();
    
        }
    
        getAllArticles(){
            this.articleService.getAllArticles().retry(3).subscribe(
                data => {this.articles = data},
                (err: HttpErrorResponse) => {
                    if (err.error instanceof Error) {
                        //A client-side or network error occurred.
                        console.log('An error occurred:', err.error.message);
                    } else {
                        //Backend returns unsuccessful response codes such as 404, 500 etc.
                        console.log('Backend returned status code: ', err.status);
                        console.log('Response body:', err.error);
                    }
                },
                        () =>console.log('done loading')
    
            );
    
        }
    }

    articles.component.html

    <table class="table">
                                    <thead>
                                    <tr>
                                        <th> Id</th>
                                        <th>Title</th>
                                        <th>Category</th>
                                        <th></th>
                                        <th></th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <tr *ngFor="let article of articles">
                                        <td>{{article.id}}</td>
                                        <td>{{article.title}}</td>
                                        <td>{{article.category}}</td>
                                    </tr>
                                    </tbody>
                                </table>

    jqxgrid.components.ts

    export class JqxgridComponent implements OnInit {
    
        public articles;
    
        public datatest = [
            {
                "title": "Android AsyncTask Example",
                "category": "Androids333",
                "id": 1
            },
            {
                "title": "vbv",
                "category": "vbv",
                "id": 7
            }
        ];
    
        constructor(private http: HttpClient, private articleService: ArticleService) {
        }
    
        ngOnInit(): void {
            this.getAllArticles();
        }
    
        getAllArticles() {
            this.articleService.getAllArticles().retry(3).subscribe(
                data => {
                    this.articles = data; console.log("data: ",data);
                },
                (err: HttpErrorResponse) => {
                    if (err.error instanceof Error) {
                        //A client-side or network error occurred.
                        console.log('An error occurred:', err.error.message);
                    } else {
                        //Backend returns unsuccessful response codes such as 404, 500 etc.
                        console.log('Backend returned status code: ', err.status);
                        console.log('Response body:', err.error);
                    }
                },
                () => console.log('done loading')
            );
    
        }
    
        source: any =
    
            {
                datatype: 'array',
                datafields: [
                    {name: 'id', type: 'int'},
                    {name: 'title', type: 'service'},
                    {name: 'category', type: 'service'}
                ],
                id: 'id',
                localdata: this.datatest
            };
    
        dataAdapter: any = new jqx.dataAdapter(this.source);
    
        cellsrenderer = (row: number, columnfield: string, value: string | number, defaulthtml: string, columnproperties: any, rowdata: any): string => {
            if (value < 20) {
                return <code><span style='margin: 4px; float:${columnproperties.cellsalign}; color: #ff0000;'>${value}</span></code>;
            }
            else {
                return <code><span style='margin: 4px; float:${columnproperties.cellsalign}; color: #008000;'>${value}</span></code>;
            }
        };
    
        columns: any[] =
            [
                {text: 'Id', datafield: 'id', width: 100},
                {
                    text: 'Title',
                    // columngroup: 'ToDoList',
                    datafield: 'title',
                    cellsalign: 'left',
                    align: 'left',
                    width: 150
                },
                {text: 'Category', datafield: 'category', align: 'center', width: 100}
            ];
    }

    jqxgrid.component.html

    <jqxGrid
                          [width]="1000" [source]="dataAdapter" [columns]="columns"
                          [pageable]="true" [autoheight]="true" [sortable]="true"
                          [altrows]="true" [enabletooltips]="true" [editable]="true"
                          [selectionmode]="'multiplecellsadvanced'">
                  </jqxGrid>
    angular jqxGrid #98491

    Ivo Zhulev
    Participant

    Hi douglas168,

    I don’t see the last thing I told you in your code. –>

    this.articleService.getAllArticles().retry(3).subscribe(
       data => {
          this.articles = data;
          this.source.localdata = data;
          this.dataAdapter.dataBind();
          // You must have a reference to the grid in order to call any of its methods/props.
          this.myGrid.updatebounddata();
       },
       .........

    Try this.

    About the error:
    (ps. I tried ‘this.source.localdata = data;’ but get Module parse failed: Unexpected token)

    The problem comes from something else in your code, so check this out carefully.

    Best Regards,
    Ivo

    jQWidgets Team
    http://www.jqwidgets.com/

Viewing 10 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic.