1

Im trying to use Angular datatable with angular2. The code is similar to this

myArray: any;

function test() {
    callService subscribe((response) => {
        this.myArray = response['body'];
    })
    this.datatableOptions();
}

datatableOptions() {
    this.dtOptions = {
        order: [1, "desc"],
        pagingType: "full_numbers",
        pageLength: 100,
        lengthMenu: [
            [100, 150, 200, -1],
            [100, 150, 200, "Todo"]
        ],
        responsive: true,
        rowCallback: function(row, data, index) {
            var api = this.api();
            $('td:eq(0)', row).html(index + (api.page() * api.page.len() + 1));
        },
        processing: true,
        searching: true,
        deferRender: true,
        data: JSON.parse(JSON.stringify(this.myArray)),
        columns: [{
                targets: 0,
                data: null
            },
            {
                targets: 1,
                data: 'A',
                defaultContent: '-'
            },
            {
                targets: 2,
                data: 'B',
                defaultContent: '-'
            },
            {
                targets: 3,
                data: 'C',
                defaultContent: '-'
            },
        ],
    }
}

The problem: console.log(response['body']) has data, but datatable doesn´t show any data. So, what´s wrong in this code?

2 Answers 2

1

It is possible the function doesn't know "this". In the subscribe function, "this" is the scope of the function, not the component.

You can avoid it with this trick:


myArray: any;

function test() {
    let thisContext = this;
    callService subscribe((response) => {
        thisContext.myArray = response['body'];
    })
    this.datatableOptions();
}

So you bind the "this" scope when you enter in the test function to the thisContext variable. Inside the subscribe function, you refer to that scope with the thisContext variable.

In this way, you should find the myArray variable populated with the data.

Sign up to request clarification or add additional context in comments.

1 Comment

Mmm, return Cannot read property 'style' of undefined
0

Add [dtTrigger]="dtTrigger" to your table tag in html.

Import this import { Subject } from 'rxjs/internal/Subject'; to your type script and initialize dtTrigger as dtTrigger: Subject<any> = new Subject();

After you assign data this.myArray = response['body']; just add this.dtTrigger.next(); to manually re-render the data.

If this still doesn't resolve the issue then destroy the data table first and manually re-render as $('#dataTableID').DataTable().clear().destroy(); this.dtTrigger.next();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.