How to display api data on children column in ag grid angular - javascript

How to call the fieldName in children or how to display.
here's the code.
list.component.ts
monthNames = new Array(
['January'], ['February'], ['March'],
['April'], ['May'], ['June'],
['July'], ['August'], ['September'],
['October'], ['November'], ['December'],
);
ngOnInit() {
this.setColumnHeader();
}
setColumnHeader() {
this.globals.getData('/users').pipe(take(1)).subscribe((data: any) => {
const record = data['data'];
record.map((x: any) => {
this.rowData.push({
'fieldName': x.firstName,
'lastName': x.lastName
});
});
});
for (let i = 0; i <= 11; i++) {
this.columnDefs.push({
'headerName': this.monthNames[i],
'field': this.monthNames[i],
'width': 100,
///child
'children': [
{
'headerName': 'Total', 'columnGroupShow': 'closed', 'field': 'total',
'valueGetter': function (params: any) {
return params.data.sample + params.data.sampleb;
}
},
{
'headerName': 'a', 'editable': true, 'columnGroupShow': 'open', 'field': 'sample',
'valueParser': this.numberParser
},
////////call the fieldName
{
///here
///the 'headerName' should be the fieldName
}
});
}
}
}
numberParser(params: any) {
return Number(params.newValue);
}
thanks in advance.

Not clear what you really want, but here you can try this.
for (let i = 0; i <= 11; i++) {
const data = {
'headerName': this.monthNames[i],
'field': this.monthNames[i],
'width': 100,
///child
'children': [
{
'headerName': 'Total', 'columnGroupShow': 'closed', 'field': 'total',
'valueGetter': function (params: any) {
return params.data.sample + params.data.sampleb;
}
},
{
'headerName': 'a', 'editable': true, 'columnGroupShow': 'open', 'field': 'sample',
'valueParser': this.numberParser
},
]
}
for (let j = 0; j < this.rowData.length; j++) {
data.children.push(
{
'headerName': this.rowData[j].fieldName, 'editable': true, 'columnGroupShow': 'open', 'field': 'sample',
'valueParser': this.rowData[j].lastName
}
)
}
this.columnDefs.push(data)
}
you can comment if this not what you expect, hope that help.

Related

Angular ngModel, 3 arrays are affected

I am creating a form builder in Angular, I used Lam Phuoc ThinhI work for reference, check his work here
<https://codepen.io/thinhlam/pen/BowEPp>
Now the problem is I have this 3 arrays, Current Field, Form Fields and Draggable Fields. Everytime I dragged a field, like for example the Header Field and then I changed the text or value of that field, the Draggable Fields is also affected. So if i dragged another Header field the value is the same with the first header field that i drag. Please check the image below.
image
app.component.html
<div *ngFor="let set of CurrentField.Settings; let i = index; trackBy:trackByIdx" [ngSwitch]="set.Type">
<div *ngSwitchCase="'textarea'" class="form-group">
<label for="textarea-{{i}}">{{set.Name}}</label>
<input [name]="'textarea' + i" type="text" class="form-control" [(ngModel)]="set.Value">
</div>
</div>
app.component.ts
FormFields: any;
CurrentField: any;
guid: number;
DragElements = [{
'Name': "Header",
"Type": "textLabel",
'Icon': "fa fa-header",
'Settings': [{
'Name': 'Field Label',
'Value': 'Header',
'Type': 'textarea'
}]
}, {
'Name': "Columns",
"Type": "columns",
'Icon': "fa fa-columns",
'Settings': [{
'Name': 'Number of Columns',
'Value': 0,
'PossibleValue': [2,3,4]
}, {
'Name': 'Column',
'Columns': []
}],
}, {
'Name': "Image",
"Type": "image",
'Icon': "fa fa-image",
'Settings': [{
'Name': 'Field Label',
'Value': 'Image',
'Type': 'textarea'
}]
}, {
'Name': "Single Text",
'Type': "text",
'Icon': "fa fa-font",
'Settings': [{
'Name': 'Field Label',
'Value': 'Single Text',
'Type': 'text'
}]
}, {
'Name': "Number",
'Type': "number",
'Icon': "fa fa-th-large",
'Settings': [{
'Name': 'Field Label',
'Value': 'Number',
'Type': 'text'
}]
}, {
'Name': "Date",
'Type': "date",
'Icon': "fa fa-calendar",
'Settings': [{
'Name': 'Field Label',
'Value': 'Date',
'Type': 'text'
}]
}, {
'Name': "Single Selection",
"Type": "dropdown",
'Icon': "fa fa-dot-circle-o",
'Settings': [{
'Name': 'Field Label',
'Value': 'Single Selection',
'Type': 'text'
}]
}, {
'Name': "Pagaraph Text",
"Type": "textarea",
'Icon': "fa fa-align-left",
'Settings': [{
'Name': 'Field Label',
'Value': 'Paragraph Text',
'Type': 'text'
}]
}];
constructor(
private cd: ChangeDetectorRef,
private zone: NgZone,
) {}
ngOnInit() {
this.CurrentField = {};
this.FormFields = [];
this.guid = 1;
}
createNewField = function() {
return {
'id': ++this.guid,
'Name': '',
'Settings': [],
'Active': true,
'ChangeFieldSetting': function(Value, SettingName) {
switch (SettingName) {
// case 'Field Label':
// this.Settings[0].Value = Value;
// // console.log(Value);
// break;
case 'Image Alignment':
this.Settings[2].DefaultAlignment = Value;
break;
case 'Columns':
let columns : any = {};
this.Settings[0].Value = Value;
for(let i = 0; i < Value; i++) {
columns = {
'ID': i + "-" + this.id,
'Title': 'Column '+i,
'Items': []
}
this.Settings[1].Columns.push(columns);
}
console.log(this);
break;
default:
break;
}
},
'GetFieldSetting': function(settingName) {
let result = {};
let settings = this.Settings;
settings.forEach((index, set) => {
if (index.Name == settingName) {
result = index;
return;
}
});
if (!Object.keys(result).length) {
settings[settings.length - 1].Options.forEach((index, set) => {
if (index.Name == settingName) {
result = index;
return;
}
});
}
return result;
}
};
}
changeFieldName = function(Value) {
this.CurrentField.Name = Value;
this.CurrentField.Settings[0].Value = this.CurrentField.Name;
}
removeElement = function(idx){
if(this.FormFields[idx].Active) {
this.CurrentField = {};
}
this.FormFields.splice(idx, 1);
};
addElement(ele, idx) {
// this.zone.run(() => {
this.CurrentField.Active = false;
this.CurrentField = this.createNewField();
Object.assign(this.CurrentField, ele);
if (idx == null) {
this.FormFields.push(this.CurrentField);
} else {
this.FormFields.splice(idx, 0, this.CurrentField);
}
// });
};
activeField = function(f) {
this.CurrentField.Active = false;
this.CurrentField = f;
f.Active = true;
};
Wherever you are using
Object.assign(this.CurrentField,ele);
like operations
deep clone before pushing.
Object.assign(this.CurrentField, JSON.parse(JSON.stringify(ele)));
This is one way of deep cloning which has its pros and cons. But your solution will be to deep clone using any suitable method.

Localization on ngx-smart-table

I'm new to Angular, I have a table that I need to display with two languages based on the user's choice, I have searched a lot for this however, couldn't find anything useful for my case, I have made a work around that doesn't really fulfill my needs as when I go to another page and then back to this page it displays the data with the wrong choice as the variable inside the localstorage returns with undefined. Please advise if you have a better approach as I totally understand that mine is really bad. Thanks in advance.
employee.component.ts
ngOnInit() {
this.switchLanguage = localStorage.getItem('selectedLanguage');
this.lang = localStorage.getItem('lang')
this.getActiveEmployees();
}
getAllEmployees(){
if(this.switchLanguage === "en" || this.browserLang === "en"){
console.log(this.switchLanguage + " Da5al hena lee 1")
this.settings = {
totalKey: 'total',
pager: {
display: true,
perPage: '5'
},
mode: 'external',
actions: false,
columns: {
firstName_FL: {
title: 'First Name',
data: this.employees.firstName_FL,
},
secondName_FL: {
title: 'Second Name',
data: this.employees.secondName_FL,
},
lastName_FL: {
title: 'Last Name',
data: this.employees.lastName_FL,
},
hiringDate: {
title: 'Hiring Date',
data: this.employees.hiringDate,
type: 'date',
filter: {
type: 'daterange'
},
valuePrepareFunction: (lastLoginTime: any) => {
return lastLoginTime.slice(0, 10)
}
},
firstContractingSalary: {
title: 'First Contracting Salary',
valuePrepareFunction: (firstContractingSalary) => {
this.formatedOutputValue = this.currenctPipe.transform(firstContractingSalary, 'EGP ',
'symbol', '1.2-2');
return this.formatedOutputValue
}
},
position: {
title: 'Position',
valuePrepareFunction: (position) => {
return position.name_FL;
},
sort: true
},
department: {
title: 'Department',
valuePrepareFunction: (department) => {
return department.name_FL;
}
},
employeeJobStatuses: {
title: 'Status',
filter: false,
sort: false,
valuePrepareFunction: (employeeJobStatuses) => {
this.statusValidation = employeeJobStatuses.map((element, i) => [
element.status
])
for(var i = 0; i < this.statusValidation.length; i++){
if(this.statusValidation[i][i] === "STATUS_ACTIVE"){
return "Active"
} else if(this.statusValidation[i][i] === "STATUS_SUSPENDED"){
return "Suspended"
} else if(this.statusValidation[i][i] === "STATUS_TERMINATED"){
return "Terminated"
} else if(this.statusValidation[i][i] === "STATUS_INACTIVE"){
return "Inactive"
}
}
}
}
}
};
} else if(this.switchLanguage === "ar" || this.browserLang === "ar"){
this.settings = {
totalKey: 'total',
pager: {
display: true,
perPage: '5'
},
mode: 'external',
actions: false,
columns: {
firstName_SL: {
title: 'الاسم الاول',
data: this.employees.firstName_SL,
},
secondName_SL: {
title: 'الاسم الاوسط',
data: this.employees.secondName_SL,
},
lastName_SL: {
title: 'الاسم الاخير',
data: this.employees.lastName_SL,
},
hiringDate: {
title: 'تاريخ التوظيف',
data: this.employees.hiringDate,
type: 'date',
filter: {
type: 'daterange'
},
valuePrepareFunction: (lastLoginTime: any) => {
return lastLoginTime.slice(0, 10)
}
},
firstContractingSalary: {
title: 'قيمة التعاقد المبدأية',
valuePrepareFunction: (firstContractingSalary) => {
this.formatedOutputValue = this.currenctPipe.transform(firstContractingSalary, 'EGP ', 'symbol', '1.2-2');
return this.formatedOutputValue
}
},
position: {
title: 'المركز',
valuePrepareFunction: (position) => {
return position.name_SL;
},
sort: true
},
department: {
title: 'القسم',
valuePrepareFunction: (department) => {
return department.name_SL;
}
},
employeeJobStatuses: {
title: 'الحالة',
filter: false,
sort: false,
valuePrepareFunction: (employeeJobStatuses) => {
this.statusValidation = employeeJobStatuses.map((element, i) => [
element.status
])
for(var i = 0; i < this.statusValidation.length; i++){
if(this.statusValidation[i][i] === "STATUS_ACTIVE"){
return "نشيط"
} else if(this.statusValidation[i][i] === "STATUS_SUSPENDED"){
return "معلق"
} else if(this.statusValidation[i][i] === "STATUS_TERMINATED"){
return "منتهي"
} else if(this.statusValidation[i][i] === "STATUS_INACTIVE"){
return "غير نشط"
}
}
}
}
}
};
}
this.translate.onLangChange.subscribe(language => {
this.browserLang = language.lang;
if(this.browserLang === "en"){
this.settings = {
totalKey: 'total',
pager: {
display: true,
perPage: '5'
},
mode: 'external',
actions: false,
columns: {
firstName_FL: {
title: 'First Name',
data: this.employees.firstName_FL,
},
secondName_FL: {
title: 'Second Name',
data: this.employees.secondName_FL,
},
lastName_FL: {
title: 'Last Name',
data: this.employees.lastName_FL,
},
hiringDate: {
title: 'Hiring Date',
data: this.employees.hiringDate,
type: 'date',
filter: {
type: 'daterange'
},
valuePrepareFunction: (lastLoginTime: any) => {
return lastLoginTime.slice(0, 10)
}
},
firstContractingSalary: {
title: 'First Contracting Salary',
valuePrepareFunction: (firstContractingSalary) => {
this.formatedOutputValue = this.currenctPipe.transform(firstContractingSalary, 'EGP ', 'symbol', '1.2-2');
return this.formatedOutputValue
}
},
position: {
title: 'Position',
valuePrepareFunction: (position) => {
return position.name_FL;
},
sort: true
},
department: {
title: 'Department',
valuePrepareFunction: (department) => {
return department.name_FL;
}
},
employeeJobStatuses: {
title: 'Status',
filter: false,
sort: false,
valuePrepareFunction: (employeeJobStatuses) => {
this.statusValidation = employeeJobStatuses.map((element, i) => [
element.status
])
for(var i = 0; i < this.statusValidation.length; i++){
if(this.statusValidation[i][i] === "STATUS_ACTIVE"){
return "Active"
} else if(this.statusValidation[i][i] === "STATUS_SUSPENDED"){
return "Suspended"
} else if(this.statusValidation[i][i] === "STATUS_TERMINATED"){
return "Terminated"
} else if(this.statusValidation[i][i] === "STATUS_INACTIVE"){
return "Inactive"
}
}
}
}
}
};
} else if(this.browserLang === "ar"){
this.settings = {
totalKey: 'total',
pager: {
display: true,
perPage: '5'
},
mode: 'external',
actions: false,
columns: {
firstName_SL: {
title: 'الاسم الاول',
data: this.employees.firstName_SL,
},
secondName_FL: {
title: 'الاسم الاوسط',
data: this.employees.secondName_SL,
},
lastName_FL: {
title: 'الاسم الاخير',
data: this.employees.lastName_SL,
},
hiringDate: {
title: 'تاريخ التوظيف',
data: this.employees.hiringDate,
type: 'date',
filter: {
type: 'daterange'
},
valuePrepareFunction: (lastLoginTime: any) => {
return lastLoginTime.slice(0, 10)
}
},
firstContractingSalary: {
title: 'قيمة التعاقد المبدأية',
valuePrepareFunction: (firstContractingSalary) => {
this.formatedOutputValue = this.currenctPipe.transform(firstContractingSalary, 'EGP ', 'symbol', '1.2-2');
return this.formatedOutputValue
}
},
position: {
title: 'المركز',
valuePrepareFunction: (position) => {
return position.name_SL;
},
sort: true
},
department: {
title: 'القسم',
valuePrepareFunction: (department) => {
return department.name_SL;
}
},
employeeJobStatuses: {
title: 'الحالة',
filter: false,
sort: false,
valuePrepareFunction: (employeeJobStatuses) => {
this.statusValidation = employeeJobStatuses.map((element, i) => [
element.status
])
for(var i = 0; i < this.statusValidation.length; i++){
if(this.statusValidation[i][i] === "STATUS_ACTIVE"){
return "نشيط"
} else if(this.statusValidation[i][i] === "STATUS_SUSPENDED"){
return "معلق"
} else if(this.statusValidation[i][i] === "STATUS_TERMINATED"){
return "منتهي"
} else if(this.statusValidation[i][i] === "STATUS_INACTIVE"){
return "غير نشط"
}
}
}
}
}
};
}
})
this.loading = true;
this.restService.GetAllEmployees().subscribe((res: any) => {
this.loading = false;
this.employees = res.data.employees;
const maw = JSON.stringify(this.employees)
this.jsonObj = JSON.parse(maw);
})
}
dont forget to inject TranslateService in ur constrctor ,and add id , name resources in ar.josn , and en.json ,try this
columnheaders:any;
ngOnInit(){
this.columnheaders = []
this.translate.get('the id').subscribe(label =>this.columnheaders[0]= label);
this.translate.get('the name').subscribe(label =>this.columnheaders[1]= label);
}
this.settings = {
columns: {
name: {
title:this.columnheaders[0],
type: 'string',
}
name: {
title:this.columnheaders[1],
type: 'string',
}
}}

Adapt React.createClass method to ES6 Class Component with react-data-grid

I am working the react-data-grid library to create an filterable datatable in react. All of their examples use the depreciated React.createClass method, and I am trying to refactor to the ES6 Class Components.
Specifically, I am trying to refactor the Filterable Grid example:
demo
source
gist of non-refactored adaption that is working
My refactored code looks like this:
import React from 'react'
import ReactDataGrid from 'react-data-grid'
const { Toolbar, Data: { Selectors } } = require('react-data-grid-addons')
class FilterableTable extends React.Component {
constructor(props) {
super(props);
this._columns = [
{
key: 'id',
name: 'ID',
width: 80
},
{
key: 'task',
name: 'Title',
editable: true
},
{
key: 'priority',
name: 'Priority',
editable: true
},
{
key: 'issueType',
name: 'Issue Type',
editable: true
},
{
key: 'complete',
name: '% Complete',
editable: true
},
{
key: 'startDate',
name: 'Start Date',
editable: true
},
{
key: 'completeDate',
name: 'Expected Complete',
editable: true
}
];
this.state = { rows: this.createRows(1001), filters: {} };
console.log(this.state);
}
getRandomDate = (start, end) => {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())).toLocaleDateString();
}
createRows = () => {
let rows = [];
for (let i = 1; i < 1000; i++) {
rows.push({
id: i,
task: 'Task ' + i,
complete: Math.min(100, Math.round(Math.random() * 110)),
priority: ['Critical', 'High', 'Medium', 'Low'][Math.floor((Math.random() * 3) + 1)],
issueType: ['Bug', 'Improvement', 'Epic', 'Story'][Math.floor((Math.random() * 3) + 1)],
startDate: this.getRandomDate(new Date(2015, 3, 1), new Date()),
completeDate: this.getRandomDate(new Date(), new Date(2016, 0, 1))
});
}
return rows;
}
getRows = () => {
return Selectors.getRows(this.state);
}
getSize = () => {
return this.getRows().length;
}
rowGetter = ( rowIdx ) => {
let rows = this.getRows();
return rows[rowIdx];
}
handleFilterChange = ({ filter }) => {
let newFilters = Object.assign({}, this.state.filters);
if (filter.filterTerm) {
newFilters[filter.column.key] = filter;
} else {
delete newFilters[filter.column.key];
}
this.setState({ filters: newFilters });
}
onClearFilters = () => {
// all filters removed
this.setState({filters: {} });
}
render() {
return (
<ReactDataGrid
columns={this._columns}
rowGetter={this.rowGetter}
enableCellSelect={true}
rowsCount={this.getSize()}
minHeight={800}
toolbar={<Toolbar enableFilter={true}/>}
onAddFilter={this.handleFilterChange}
onClearFilters={this.onClearFilters} />);
}
}
export default FilterableTable
Issue:
An issue arises when I click the filter button - a new header row is rendered (via the Toolbar component), but there is no input field. This screenshot shows the two examples side by side - my ES6 version on top and the createClass version on the bottom:
I am not sure what is causing this, but have a feeling it might be due to the way I am importing Toolbar ? Any help or a point in the right direction would be greatly appreciated ! (As well as any other suggestions re refactoring this component.)
To enable filtering for a given column, you need to set filterable=true for that column. So, add filterable:true to each object in this._columns. For more info, check http://adazzle.github.io/react-data-grid/examples.html#/filterable-grid.
this._columns = [
{
key: 'id',
name: 'ID',
width: 80
},
{
key: 'task',
name: 'Title',
editable: true,
filterable:true
},
{
key: 'priority',
name: 'Priority',
editable: true,
filterable:true
},
{
key: 'issueType',
name: 'Issue Type',
editable: true,
filterable:true
},
{
key: 'complete',
name: '% Complete',
editable: true,
filterable:true
},
{
key: 'startDate',
name: 'Start Date',
editable: true,
filterable:true
},
{
key: 'completeDate',
name: 'Expected Complete',
editable: true,
filterable:true
}
];

Checkbox in tinymce popup window

I would like to create checkbox in popup window using tinymce. I can create listbox in popup window but cannot create checkbox in it.
var tempGroups = ['Group1', 'Group2', 'Group3', 'Group4'];
var temp = [{
group: 'Group1',
title: 'Title1',
content: '<p>Content1</p>',
}, {
group: 'Group1',
title: 'Title1-1',
content: '<p>Content11</p>',
}, {
group: 'Group2',
title: 'Title2',
content: '<p>Content2</p>'
}, {
group: 'Group2',
title: 'Title2-1',
content: '<p>Content22</p>'
}, {
group: 'Group3',
title: 'Title3-1',
content: '<p>Content33</p>'
}, {
group: 'Group4',
title: 'Title4',
content: '<p>Content4</p>'
}, {
group: 'Group4',
title: 'Title4-1',
content: '<p>Content44</p>'
}];
var tempGroupName;
var menuItems = [];
function createTempMenu(editor) {
for (i = 0; i < tempGroups.length; i++) {
var tempArray = [];
tempArray[i] = [];
tempGroupName = tempGroups[i];
for (j = 0; j < temp.length; j++) {
if (temp[j].group == tempGroupName) {
tempArray[i].push({
text: temp[j].title,
content: temp[j].content,
// type: 'checkbox',
onclick: function () {
alert(this.settings.content);
}
});
}
}
menuItems[i] = {
text: tempGroupName,
menu: tempArray[i],
};
}
return menuItems;
}
tinymce.init({
selector: "textarea",
setup: function (editor) {
editor.addButton('button', {
type: 'menubutton',
text: 'button',
icon: false,
menu: [
{
text: 'Customer List',
onclick: function () {
editor.windowManager.open({
title: 'Customer Name',
width: 200,
height: 100,
items: [
{
type: 'listbox',
value: 0,
label: 'Section: ',
values: createTempMenu(editor),
body: [
{
type: 'checkbox',
label: 'Section: ',
// text: "new",
values: createTempMenu(editor),
}],
onsubmit: function (e) {
}
}]
});
}
}]
});
},
toolbar: " button "
});
Any help will be appreciated.
An old question just found it. If you're still looking for an answer you can refer to their reference Here it has further details
There's a type called checkbox in tinymce
{
type : 'checkbox',
name : 'choose the name',
label : 'choose a label',
text : 'the text near the checkbox',
checked : false
},

How to add content in dynamic tab

I have a jqQrid that I have placed inside a HTML table. Now as per my requirement I have to show this grid inside the dynamic tab which is opened on hyper link click.
Here is the code for dynamic tab creation:
function addTab(title) {
if ($('#tt').tabs('exists', title)) {
$('#tt').tabs('select', title);
}
else {
if (title == "Check in List") {
//Here i have to call jqgrid loading function but how I am not getting !!!
var content = '';
}
else {
var content = '<p>Hii</p>';
}
$('#tt').tabs('add', {
title: title,
content: content,
closable: true
});
}
}
Here is the function to generate the grid:
function CheckInRecordgrid() {
//Grid Codes
}
And here is the HTML table placeholder:
<table id="CheckIngrid"></table>
Now my question is how to call the grid generation function if the clicked tab is as per the condition?
Here is my full grid code..
function CheckInRecordgrid() {
var data = [[48803, "DELUX", "A", "2014-09-12 12:30:00", "Done"], [48804, "NORAML", "V", "2014-09-12 14:30:00", "Pending"]];
$("#CheckIngrid").jqGrid({
datatype: "local",
height: '100%',
autowidth: true,
colNames: ['Room No.', 'Category', ' Guest name', ' Date & Time ', 'Status'],
colModel: [
{
name: 'Room No.', index: 'Room No.', width: 100, align: 'center'
},
{
name: 'Category', index: 'Category', width: 100, align: 'center'
},
{
name: 'Guest name', index: 'Guest name', width: 100, align: 'center'
},
{
name: 'Date & Time', index: 'Date & Time', width: 100, align: 'center'
},
{
name: 'status', index: 'status', width: 100, align: 'center'
}
],
caption: "Check In List"
});
var names = ["Room No.", "Category", "Guest name", "Date & Time", "status"];
var mydata = [];
for (var i = 0; i < data.length; i++) {
mydata[i] = {};
for (var j = 0; j < data[i].length; j++) {
mydata[i][names[j]] = data[i][j];
}
}
for (var i = 0; i <= mydata.length; i++) {
$("#CheckIngrid").jqGrid('addRowData', i + 1, mydata[i]);
}
}
try this
if (title == "Check in List") {
var content = '';
}else {
var content = '<p>Hii</p>';
};
$('#tt').tabs('add', {
title: title,
content: content,
closable: true,
}).tabs({
onAdd: function(title,index){
if (title == "Check in List") {
CheckInRecordgrid();
}
}
});

Categories

Resources