Commit 4f17325d by Nattana Chaiyamat

syncfution

parent dcd55187
import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, } from '@angular/core';
import { ColumnModel } from '@syncfusion/ej2-grids';
import { ar } from 'date-fns/locale';
import { ToastrService } from 'ngx-toastr';
import { Bu1Model, MyBu1Model } from 'src/app/shared/model/bu1.model';
import { Bu1Service } from 'src/app/shared/services/bu1.service';
......@@ -13,19 +15,34 @@ export class DepartmentRegisterComponent implements OnInit {
currentPage = 1
pageSize = 10
page = Array.from({ length: 1 }, (_, i) => i + 1);
bu1List: { check: boolean, data: Bu1Model }[] = []
bu1ListLoading = false
bu1: Bu1Model = new MyBu1Model()
search = ""
selectedFile: File | null = null;
selectedFileName: string = 'กรุณาเลือกไฟล์';
selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
currentModel: 'add' | 'edit' | 'delete' = "add"
bu1: { loading: boolean, select: Bu1Model, dataList: Bu1Model[] } = { loading: false, select: new MyBu1Model(), dataList: [] }
columns: ColumnModel[] = [{
"field": "bu1id",
"headerText": "รหัสกลุ่มการอนุมัติ",
isPrimaryKey: true,
},
{
"field": "tdesc",
"headerText": "รายละเอียดฝ่าย(ไทย)"
},
{
"field": "edesc",
"headerText": "รายละเอียดฝ่าย(อังกฤษ)"
}]
searchSettings = {
fields: ['bu1id', 'tdesc', 'edesc'],
operator: 'contains',
ignoreCase: true,
// customMatchCase: (cellValue: string, searchValue: string) => {
// return cellValue.toString().toLowerCase() === '00';
// }
currentModel: 'add' | 'edit' | 'delete' | 'deleteGroup' = "add"
numDataListChecked = 0
isDataListChecked = false
isDataListCheckedAll = false
};
constructor(private bu1Service: Bu1Service,
private toastr: ToastrService,
private cdr: ChangeDetectorRef,
......@@ -46,7 +63,7 @@ export class DepartmentRegisterComponent implements OnInit {
}
const formData = new FormData();
formData.append('file', this.selectedFile);
this.bu1ListLoading = true
this.bu1.loading = true
this.fileService.uploadExcel(formData, 'mbu1').subscribe({
next: response => {
if (response.success) {
......@@ -54,11 +71,11 @@ export class DepartmentRegisterComponent implements OnInit {
this.getBu1List()
} else {
this.showAlert(response.message, 'error')
this.bu1ListLoading = false
this.bu1.loading = false
}
}, error: error => {
this.showAlert(error.message, 'error')
this.bu1ListLoading = false
this.bu1.loading = false
}
})
}
......@@ -84,36 +101,37 @@ export class DepartmentRegisterComponent implements OnInit {
getBu1List() {
this.bu1ListLoading = true
this.bu1.loading = true
this.bu1Service.getList().subscribe({
next: response => {
this.bu1List = response.map(x => ({ check: false, data: new MyBu1Model(x) }))
this.isDataListCheckedAll = false
this.dataListCheckAll()
this.bu1ListLoading = false
this.bu1.dataList = response.map(x => {
this.selectedItems.data.set(x.bu1id, false)
return new MyBu1Model(x)
})
this.selectedItems.key = 'bu1id'
console.log(" 🐒 this.selectedItems:", this.selectedItems)
this.bu1.loading = false
this.searchChange()
this.cdr.detectChanges()
}, error: error => {
this.bu1ListLoading = false
this.bu1.loading = false
this.cdr.detectChanges()
}
})
}
searchChange() {
this.currentPage = 1
this.page = Array.from({ length: Math.ceil(this.bu1ListFilter().length / 10) }, (_, i) => i + 1);
this.dataListCheck()
this.page = Array.from({ length: Math.ceil(this.bu1ListFilter().length / 10) }, (_, i) => i + 1)
}
bu1ListFilter() {
return this.bu1List.filter(x => {
const data = x.data
return data.bu1id.toLowerCase().includes(this.search.toLowerCase()) ||
data.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
data.edesc.toLowerCase().includes(this.search.toLowerCase())
return this.bu1.dataList.filter(x => {
return x.bu1id.toLowerCase().includes(this.search.toLowerCase()) ||
x.tdesc.toLowerCase().includes(this.search.toLowerCase()) ||
x.edesc.toLowerCase().includes(this.search.toLowerCase())
})
}
selectBu1(bu1?: Bu1Model) {
this.bu1 = new MyBu1Model(bu1)
this.bu1.select = new MyBu1Model(bu1)
}
showAlert(text: string, type: 'success' | 'error') {
......@@ -123,55 +141,53 @@ export class DepartmentRegisterComponent implements OnInit {
})
}
addBu1() {
this.bu1ListLoading = true
this.bu1Service.post(this.bu1).subscribe({
this.bu1.loading = true
this.bu1Service.post(this.bu1.select).subscribe({
next: response => {
if (response.success) {
this.showAlert(response.message, 'success')
this.getBu1List()
} else {
this.showAlert(response.message, 'error')
this.bu1ListLoading = false
this.bu1.loading = false
}
}, error: error => {
this.showAlert(error.message, 'error')
this.bu1ListLoading = false
this.bu1.loading = false
}
})
}
deleteBu1() {
this.bu1ListLoading = true
const body = this.bu1List.filter(x => x.check).map(x => new MyBu1Model(x.data))
this.bu1Service.delete(body).subscribe({
next: response => {
if (response.success) {
this.showAlert(response.message, 'success')
this.getBu1List()
} else {
this.showAlert(response.message, 'error')
this.bu1ListLoading = false
}
}, error: error => {
this.showAlert(error.message, 'error')
this.bu1ListLoading = false
}
})
}
dataListCheckAll() {
const selectAll = this.isDataListCheckedAll;
this.bu1ListFilter().forEach(x => x.check = selectAll);
this.dataListCheck();
}
dataListCheck() {
const dataCheck = this.bu1ListFilter();
this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x.check) : false;
this.numDataListChecked = this.bu1List.filter(x => x.check).length
this.isDataListChecked = Boolean(this.numDataListChecked)
this.bu1.loading = true
const body = this.bu1.dataList.filter(x => {
if (Array.from(this.selectedItems.data.keys()).find((y: any) => y == x.bu1id) && Array.from(this.selectedItems.data.values()).find((y: any) => y)) {
return true
}
return false
}
).map(x => new MyBu1Model(x))
console.log(" 🐒 body:", body)
// this.bu1Service.delete(body).subscribe({
// next: response => {
// if (response.success) {
// this.showAlert(response.message, 'success')
// this.getBu1List()
// } else {
// this.showAlert(response.message, 'error')
// this.bu1.loading = false
// }
// }, error: error => {
// this.showAlert(error.message, 'error')
// this.bu1.loading = false
// }
// })
}
checkPrimary() {
return this.bu1List.find(x => x.data.bu1id == this.bu1.bu1id)
return this.bu1.dataList.find(x => x.bu1id == this.bu1.select.bu1id)
}
onSelectItemChange(arg: any) {
this.selectedItems = arg
}
}
\ No newline at end of file
<ejs-grid #grid id='Grid' [dataSource]="dataSource" [allowFiltering]="allowFiltering" [filterSettings]="filterSettings"
[groupSettings]="groupSettings" [toolbar]='toolbarOptions' [editSettings]="editSettings"
(actionBegin)="onActionBegin($event)" (actionComplete)="onActionComplete($event)"
(rowSelected)="onRowSelectedCheckbox($event.data)" (rowDeselected)="onRowDeselectedCheckbox($event.data)"
showColumnMenu='true' allowPaging='true' allowGrouping='true' allowSorting='true' showColumnMenu='true'
allowFiltering='true' [allowPdfExport]='true' (toolbarClick)='toolbarClick($event)' [allowExcelExport]='true'
[selectionSettings]="selectionOptions" (detailDataBound)='detailDataBound($event)' width="auto" allowReordering='true'
[loadingIndicator]='loadingIndicator' [query]="query" rowHeight='60' allowEditing='false' [pageSettings]='initialPage'
[allowMultiSorting]='true'>
[searchSettings]="searchSettings" [groupSettings]="groupSettings" [toolbar]='toolbarOptions'
[editSettings]="editSettings" showColumnMenu='true' allowPaging='true' allowGrouping='true' allowSorting='true'
showColumnMenu='true' allowFiltering='true' [allowPdfExport]='true' (toolbarClick)='toolbarClick($event)'
[allowExcelExport]='true' [selectionSettings]="selectionOptions" (detailDataBound)='detailDataBound($event)'
width="auto" allowReordering='true' [loadingIndicator]='loadingIndicator' [query]="query" rowHeight='60'
allowEditing='false' [pageSettings]='initialPage' [allowMultiSorting]='true'>
<e-columns>
<e-column type='checkbox' width='50' *ngIf="checkBoxSetting"></e-column>
<!-- <e-column type='checkbox' width='50' *ngIf="checkBoxSetting"></e-column> -->
<e-column [textAlign]="'center'" *ngIf="checkBoxSetting" [allowEditing]="false">
<ng-template #headerTemplate let-data>
<input type="checkbox" [id]="'checkbox-all'" class="ti-form-checkbox cursor-pointer"
[checked]="selectedItemsAll" (click)="toggleSelectionAll()">
<label [for]="'checkbox-all'" class="text-sm text-gray-500 mx-2">
{{selectedItems.count}} Selected</label>
</ng-template>
<ng-template #template let-data>
<input type="checkbox" class="ti-form-checkbox cursor-pointer"
[checked]="selectedItems.data.get(data[selectedItems.key]) || false"
(click)="toggleSelection(data[selectedItems.key], !selectedItems.data.get(data[selectedItems.key]))">
</ng-template>
</e-column>
<e-column *ngFor="let col of columns" [field]="col.field" [headerText]="col.headerText" [width]="col.width"
[format]="col.format" [textAlign]="'center'" [isPrimaryKey]="col.isPrimaryKey" [editType]="col.editType"
[validationRules]="col.validationRules" [allowEditing]="'true'" [allowSorting]="'true'" [allowFiltering]="true"
......@@ -24,10 +35,8 @@
</ng-template>
<ng-template #template let-data>
<i class="ti ti-eye cursor-pointer i-gray fs-l px-1" (click)="onNextPage(data)" *ngIf="canChild"></i>
<i class="ti ti-edit cursor-pointer i-gray fs-l px-1" data-hs-overlay="#modal-detail" *ngIf="canEdit"
(click)="onViewSelected(data)"></i>
<i class="ti ti-trash cursor-pointer i-gray fs-l px-1" data-hs-overlay="#modal-delete" *ngIf="canDelete"
(click)="onRemoveSelected(data)"></i>
<i class="ti ti-edit cursor-pointer i-gray fs-l px-1" [attr.data-hs-overlay]="modalName" *ngIf="canEdit"
(click)="onSelectData(data)"></i>
</ng-template>
</e-column>
</e-columns>
......
......@@ -10,8 +10,9 @@ import {
} from '@angular/core';
import { EditService, ReorderService, SortService, GroupService, ColumnMenuService, PageService, FilterService, SelectionSettingsModel, ToolbarItems, ToolbarService, GridComponent, PdfExportService, ExcelExportService, DetailRowService, DetailDataBoundEventArgs, Grid, AggregateService, PdfExportProperties, LoadingIndicatorModel } from '@syncfusion/ej2-angular-grids';
import { GroupSettingsModel, FilterSettingsModel, ColumnModel } from '@syncfusion/ej2-angular-grids';
import { Query } from '@syncfusion/ej2-data';
import { DataManager, Query } from '@syncfusion/ej2-data';
import { L10n, setCulture } from '@syncfusion/ej2-base';
setCulture('th-TH');
L10n.load({
......@@ -51,28 +52,31 @@ L10n.load({
encapsulation: ViewEncapsulation.None
})
export class DatagridSyncfutionComponent implements OnInit {
/**
* ======================
* @Input() ส่วนรับค่า
* ======================
*/
@ViewChild('grid') public grid?: GridComponent;
@Input() dataSource: any[] = [];
@Output() sendSelectData = new EventEmitter<any>();
@Input() columns: ColumnModel[] = [];
// @Input() toolbarOptions?: ToolbarItems[]
@Input() toolbarOptions?: ToolbarItems[] = ['Print', 'ExcelExport', 'CsvExport'];
@Input() searchSettings = {}
@Input() selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };
selectedItemsAll = false
@Output() sendSelectedItems = new EventEmitter<any>();
@Input() modalName = ''
@Input() checkBoxSetting = true
@Input() actionSetting = true
@Input() detailSetting = false
@Input() childList = ''
@Input() searchText = ''
@Input() dataSource: any[] = []; // ข้อมูลที่จะแสดงในตาราง
@Input() columns: ColumnModel[] = []; // กำหนดโครงสร้างของคอลัมน์
@Input() childColumns: ColumnModel[] = [];
@Input() allowSorting = true;
@Input() allowFiltering = true;
@Input() filterSettings?: FilterSettingsModel = { type: 'Excel' };;
@Input() groupSettings?: GroupSettingsModel = { allowReordering: true, showGroupedColumn: true, showDropArea: false };
public selectionOptions?: SelectionSettingsModel = { checkboxOnly: true };
// ตัวอย่างการตั้งค่าอื่น ๆ ตามต้องการ
@Input() toolbarOptions?: ToolbarItems[] = ['Print', 'ExcelExport', 'CsvExport'];
@Input() editSettings? = { allowEditing: true, mode: 'Batch' };
@Input() initialPage? = { pageSizes: true, pageSize: 10 };
@Input() canDelete = true
......@@ -80,23 +84,13 @@ export class DatagridSyncfutionComponent implements OnInit {
@Input() canEdit = true
// ... เป็นต้น
public query: Query = new Query().addParams('dataCount', '1000');
loadingIndicator : LoadingIndicatorModel = { indicatorType: 'Shimmer' };
/**
* ======================
* @Output() ส่วนส่ง Event
* ======================
*/
// ตัวอย่าง event เมื่อเลือกแถว
@Output() rowSelected = new EventEmitter<any>();
@Output() childSelected = new EventEmitter<any>();
@Output() rowRemoveSelected = new EventEmitter<any>();
@Output() rowSelectedCheckbox = new EventEmitter<any>();
@Output() rowDeselectedCheckbox = new EventEmitter<any>();
loadingIndicator: LoadingIndicatorModel = { indicatorType: 'Shimmer' };
// ตัวอย่าง event เมื่อมีการลบ / แก้ไข
@Output() actionBegin = new EventEmitter<any>();
@Output() actionComplete = new EventEmitter<any>();
public selectedRecord?: any;
// อาจมี event อื่น ๆ เช่น pageChange, filterChange, ฯลฯ
// แล้วแต่ logic ที่ต้องการให้ parent รู้
// @Output() pageChanged = new EventEmitter<number>();
......@@ -111,93 +105,45 @@ export class DatagridSyncfutionComponent implements OnInit {
}
ngOnChanges(changes: SimpleChanges): void {
console.log(changes)
this.query = new Query().addParams('dataCount', '1000');
this.loadingIndicator = {indicatorType: 'Shimmer'};
this.loadingIndicator = { indicatorType: 'Shimmer' };
if (changes) {
console.log('this.dataSource', this.dataSource)
if (changes['searchText']) {
this.search(changes['searchText'].currentValue)
}
}
//Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here.
//Add '${implements OnChanges}' to the class.
}
/**
* =============================
* ฟังก์ชันที่ผูกกับ Event ของ <ejs-grid>
* =============================
*/
public onViewSelected(args: any) {
// เมื่อมีการ select row
this.rowSelected.emit(args);
}
public onNextPage(args: any) {
// เมื่อมีการ select row
this.childSelected.emit(args);
}
public onRemoveSelected(args: any) {
// เมื่อมีการ select row
this.rowRemoveSelected.emit(args);
}
public onRowSelectedCheckbox(args: any) {
// เมื่อมีการ select row
this.rowSelectedCheckbox.emit(args);
}
public onRowDeselectedCheckbox(args: any) {
// เมื่อมีการ select row
this.rowDeselectedCheckbox.emit(args);
}
public onActionBegin(args: any) {
this.actionBegin.emit(args);
onSelectData(args: any) {
this.sendSelectData.emit(args);
}
public onActionComplete(args: any) {
this.actionComplete.emit(args);
onNextPage(args: any) {
console.log(args)
}
toolbarClick(args: any): void {
// if (args.item.id === 'Grid_pdfexport') { // 'Grid_pdfexport' -> Grid component id + _ + toolbar item name
// const pdfExportProperties: PdfExportProperties = {
// exportType: 'CurrentPage'
// };
// this.grid/pdfExport(pdfExportProperties);
// }
if (args.item.id === 'Grid_excelexport') {
// 'Grid_excelexport' -> Grid component id + _ + toolbar item name
this.grid?.excelExport();
}
else if (args.item.id === 'Grid_csvexport') {
// 'Grid_csvexport' -> Grid component id + _ + toolbar item name
this.grid?.csvExport();
}
// (this.grid as GridComponent).excelExport();
}
showDetails(data: any) {
console.log(data)
this.selectedRecord = data;
this.rowSelected.emit(this.selectedRecord);
}
search(text?: string) {
if(text){
(this.grid as GridComponent).search(text);
search(text: string) {
if (this.grid) {
(this.grid as GridComponent).search(this.searchText);
// let filteredData = (this.grid as GridComponent).getCurrentViewRecords();
// console.log(filteredData);
// const clonedData = JSON.parse(JSON.stringify(this.dataSource));
// new DataManager(clonedData).executeQuery(new Query().search(this.searchText, [], undefined, true)).then((e: any) => {
// console.log('Searched Records:', e.result)
// });
}
}
detailDataBound(e: DetailDataBoundEventArgs) {
console.log(e)
let detail = new Grid({
// ─────────────────────────────────────────────────────────────
// เดิมเป็น data.filter(...) เทียบ EmployeeID
......@@ -219,5 +165,18 @@ export class DatagridSyncfutionComponent implements OnInit {
// detail.appendTo((e.detailElement as HTMLElement).querySelector('.custom-grid') as HTMLElement);
}
toggleSelection(key: string, value: boolean) {
this.selectedItems.data.set(key, value);
this.selectedItems.count = Array.from(this.selectedItems.data.values()).filter(v => v).length;
this.sendSelectedItems.emit(this.selectedItems);
}
toggleSelectionAll() {
this.selectedItemsAll = !this.selectedItemsAll;
this.selectedItems.data.forEach((_, key) => {
this.selectedItems.data.set(key, this.selectedItemsAll);
});
this.selectedItems.count = this.selectedItemsAll ? this.selectedItems.data.size : 0;
this.sendSelectedItems.emit(this.selectedItems);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment