0

I have a function that creates random values but I want to know how to add this function when I create a new record in a ng2-smart-table. I'm creating users and I need to assign them a random id.

This is my random id code:

stringGen(len) {
    var text = "";

    var charset = "abcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < len; i++)
      text += charset.charAt(Math.floor(Math.random() * charset.length));

    return text;
  }

  randomID = this.stringGen(8);

this is my html: list-user.component.html

<ng2-smart-table 
[settings]="settings" 
[source]="roles">
</ng2-smart-table>

this is my ts: list-user.component.ts

settings = {
    columns: { 
        role_id : { 
            title: 'Role ID',
        }, 
        role_desc : {
            title: 'Role Description',
            editor: {
                type: 'textarea',
            }
        }
    }
}
Hacène
  • 253
  • 1
  • 8

1 Answers1

0

You can use the createConfirm event to run code when a new record is created in the ng2-smart-table.

Your template would look like this:

<ng2-smart-table [settings]="tableSettings" [source]="tableSource" (createConfirm)="onCreateConfirm($event)"></ng2-smart-table>

And in your component:

onCreateConfirm($event: any) {
    // `$event.newData` carries information the user wants to add to the table.
}

You can create the record with the ID generated by your stringGen() function in there, add it to the table source and load the source again to get the new record in the table with the randomly generated ID.

Hacène
  • 253
  • 1
  • 8