기초튜토리얼 Angular DataGrid 응용 프로그램에서 색 드롭다운 목록을 만드는 방법
페이지 정보
작성자 GrapeCity 작성일 2023-10-10 09:28 조회 127회 댓글 0건본문
관련링크
선택할 색이 포함된 드롭다운을 만들기 위해서는 FlexGrid에 셀이 필요합니다.
를 사용하는 방법이 있고, 또 다른 방법은 이번 스터디에서 사용할 를 사용하는 방법이 있습니다.
Wijmo의 ComboBox 컨트롤은 입력(Input) 요소와 드롭다운 목록을 결합합니다.
이를 통해 목록에서 문자열 또는 개체를 선택하고 편집할 수 있습니다.
비슷한 방법을 사용하여 다른 아이콘을 추가하고 사용자 정의를 통해 그리드 및 ComboBox의 보기를 변경할 수 있습니다.
시작하기
평소처럼 FlexGrid를 만들고, 색을 표시할 열에서 다음 속성을 설정합니다.
<wj-flex-grid-column header="Color Dropdown" [binding]="'colorsMapped'" [editor]="theColorCombo" ></wj-flex-grid-column>
- header: 헤더 제목을 표시합니다.
- [binding]: app.component.ts 파일에서 열이 바인딩될 값입니다.
[editor]: 수정할 열을 의미하며, app.component.html 파일에 있는 콤보 상자에도 할당됩니다.
콤보 상자를 app.component.html 파일에도 추가하고 다음 속성을 설정합니다.
<wj-combo-box #theColorCombo [itemsSource]="colors" [displayMemberPath]="'name'" (initialized)="initCombo(theColorCombo)" (formatItem)="formatCombo(theColorCombo, $event)" ></wj-combo-box>
- #id는 에디터로서 열을 이 콤보 상자에 연결합니다.
- [itemSource]: 바인딩할 데이터입니다.
- [displayMemberPath]: 드롭다운에 텍스트로 표시될 멤버(속성)를 지정합니다.
- (initialized): 컴포넌트가 초기화된 경우 실행되는 이벤트입니다.
- (formatItem): 그리드에서 셀이 렌더링될 때마다 실행되고 사용자가 콘텐츠를 수정할 수 있도록 허용합니다.
이제 이 콤보 상자를 작동할 코드가 필요합니다.
먼저 app.component.ts 파일에서 다음 코드를 추가합니다.
import { Component, ElementRef } from '@angular/core'; import { DataSvcService } from './data-svc.service'; import * as wjCore from '@grapecity/wijmo'; import * as wjGrid from '@grapecity/wijmo.grid'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { data: any; grid: any; colors; constructor(private dataSvc: DataSvcService, private el: ElementRef) { this.data = new wjCore.CollectionView(dataSvc.getData(10500)); this.colors = dataSvc.getColorMap(); } }
여기서, 모듈 가져오기를 추가하고, 생성자에 종속성을 삽입합니다.
그리고 데이터 및 색 변수에 데이터를 할당합니다.
그런 다음, 아래 코드를 추가하겠습니다.
gridInit(grid) { this.grid = grid; grid.formatItem.addHandler((s, e) => { let col = s.columns[e.col], row = s.rows[e.row]; if ( e.panel.cellType == wjGrid.CellType.Cell && col.binding == 'colorsMapped' ) { let colorName = this.findCorrespondingColor(row.dataItem[col.binding]); colorName = colorName ? colorName.color : e.cell.textContent; let html = wjCore.format( `<span class='coloritem' style='background:${colorName};'></span><span class='colorname'> ${e.cell.textContent}</span>`, e.data, (data, name, fmt, val) => { return wjCore.isString(data[name]) ? wjCore.escapeHtml(data[name]) : val; } ); let colorBoxhtml = document.createElement('div'); colorBoxhtml.className = 'colorDiv'; colorBoxhtml.innerHTML = html; e.cell.insertBefore(colorBoxhtml, e.cell.firstChild); e.cell.lastChild.textContent = ''; //update background color of cell according to cell data e.cell.style.backgroundColor = colorName; } else { e.cell.style.backgroundColor = ''; } }); }
FlexGrid가 초기화되면 gridInit()
함수가 호출됩니다.
여기에서 열의 속성을 결정하고, 적절한 설정을 위한 로직을 추가합니다.
다른 코드를 작동하기 위한 나머지 메서드를 추가합니다.
initCombo(cb) { //update color icon initially this.addCustomColorIcon(cb); //handle of item change from dropdown cb.selectedIndexChanged.addHandler((s, e) => { let colorDiv = s.hostElement.querySelector('.colorDivCb'); if (colorDiv) { colorDiv.remove(); } this.addCustomColorIcon(s); }); } addCustomColorIcon(comboBox) { let item = comboBox.selectedItem; let colorBoxhtml = document.createElement('div'); colorBoxhtml.className = 'colorDivCb'; colorBoxhtml.innerHTML = `<span class='coloritem' style='background:${item.color};'>`; comboBox.inputElement.parentElement.insertBefore( colorBoxhtml, comboBox.inputElement ); } formatCombo(s, e) { let html = wjCore.format( "<span class='coloritem' style='background:{color};'></span><span class='colorname'> {name}</span>", e.data, (data, name, fmt, val) => { return wjCore.isString(data[name]) ? wjCore.escapeHtml(data[name]) : val; } ); e.item.innerHTML = html; }
이 코드에는 comboBox가 초기화될 때 호출되는 initCombo
가 있습니다.
또한 initCombo
함수에서 사용되는 div를 만들고 스타일 지정을 위한 클래스를 추가하는 addCustomColorIcon
함수도 있습니다.
마지막으로 app.component.html에서 이벤트가 표시를 위해 셀의 형식을 지정할 수 있는 지시문인 formatCombo
가 있습니다.
완료된 파일은 다음과 같습니다.
import { Component, ViewChild, ElementRef } from '@angular/core'; import { DataSvcService } from './data-svc.service'; import * as wjCore from '@grapecity/wijmo'; import * as wjGrid from '@grapecity/wijmo.grid'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { data: any; grid: any; colors; constructor(private dataSvc: DataSvcService, private el: ElementRef) { this.data = new wjCore.CollectionView(dataSvc.getData(10500)); this.colors = dataSvc.getColorMap(); } gridInit(grid) { this.grid = grid; grid.formatItem.addHandler((s, e) => { let col = s.columns[e.col], row = s.rows[e.row]; if ( e.panel.cellType == wjGrid.CellType.Cell && col.binding == 'colorsMapped' ) { let colorName = this.findCorrespondingColor(row.dataItem[col.binding]); colorName = colorName ? colorName.color : e.cell.textContent; let html = wjCore.format( `<span class='coloritem' style='background:${colorName};'></span><span class='colorname'> ${e.cell.textContent}</span>`, e.data, (data, name, fmt, val) => { return wjCore.isString(data[name]) ? wjCore.escapeHtml(data[name]) : val; } ); let colorBoxhtml = document.createElement('div'); colorBoxhtml.className = 'colorDiv'; colorBoxhtml.innerHTML = html; e.cell.insertBefore(colorBoxhtml, e.cell.firstChild); e.cell.lastChild.textContent = ''; //update background color of cell according to cell data e.cell.style.backgroundColor = colorName; } else { e.cell.style.backgroundColor = ''; } }); } findCorrespondingColor(name) { return this.colors.filter((i) => i.name == name)[0]; } initCombo(cb) { //update color icon initially this.addCustomColorIcon(cb); //handle of item change from dropdown cb.selectedIndexChanged.addHandler((s, e) => { let colorDiv = s.hostElement.querySelector('.colorDivCb'); if (colorDiv) { colorDiv.remove(); } this.addCustomColorIcon(s); }); } addCustomColorIcon(comboBox) { let item = comboBox.selectedItem; let colorBoxhtml = document.createElement('div'); colorBoxhtml.className = 'colorDivCb'; colorBoxhtml.innerHTML = `<span class='coloritem' style='background:${item.color};'>`; comboBox.inputElement.parentElement.insertBefore( colorBoxhtml, comboBox.inputElement ); } formatCombo(s, e) { let html = wjCore.format( "<span class='coloritem' style='background:{color};'></span><span class='colorname'> {name}</span>", e.data, (data, name, fmt, val) => { return wjCore.isString(data[name]) ? wjCore.escapeHtml(data[name]) : val; } ); e.item.innerHTML = html; } }
이러한 메서드는 요구 사항에 맞게 콤보 상자의 데이터 및 속성의 형식을 지정합니다.
코드를 참조하고, 여러분의 필요에 맞게 조정해 보세요.
다음은 app.component.html 파일의 예제입니다.
<wj-flex-grid #grid [itemsSource]="data" (initialized)="gridInit(grid)"> <wj-flex-grid-filter></wj-flex-grid-filter> <wj-flex-grid-column [header]="'Id'" [binding]="'id'"></wj-flex-grid-column> <wj-flex-grid-column [header]="'Colors Mapped'" [binding]="'colorsMapped'" [width]="250" [editor]="theColorCombo" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Country'" [binding]="'country'" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Date'" [binding]="'date'" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Time'" [binding]="'time'" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Sales'" [binding]="'sales'" format="n2" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Expenses'" [binding]="'expenses'" format="n2" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Time'" [binding]="'time'" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Time'" [binding]="'time'" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Sales'" [binding]="'sales'" format="n2" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Expenses'" [binding]="'expenses'" format="n2" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Time'" [binding]="'time'" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Time'" [binding]="'time'" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Sales'" [binding]="'sales'" format="n2" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Expenses'" [binding]="'expenses'" format="n2" ></wj-flex-grid-column> <wj-flex-grid-column [header]="'Time'" [binding]="'time'" ></wj-flex-grid-column> </wj-flex-grid> <!-- custom editors --> <wj-combo-box #theColorCombo [itemsSource]="colors" [displayMemberPath]="'name'" (initialized)="initCombo(theColorCombo)" (formatItem)="formatCombo(theColorCombo, $event)" ></wj-combo-box>
FlexGrid의 데이터와 관련하여 도움이 되는 data-svc.service.ts 파일입니다.
import { Injectable } from '@angular/core'; @Injectable() export class DataSvcService { constructor() {} getData(count): any[] { // create some random data var countries = 'US,Germany,UK,Japan,Italy,Greece'.split(','), colors = this.getColorMap(), data = []; for (var i = 0; i < count; i++) { data.push({ id: i, date: new Date(2015, i % 12, (i + 1) % 25), time: new Date(2015, i % 12, (i + 1) % 25, i % 24, i % 60, i % 60), country: countries[i % countries.length], colorsMapped: colors[i % colors.length].name, downloads: Math.round(Math.random() * 20000), sales: Math.random() * 10000, expenses: Math.random() * 5000, checked: i % 9 == 0, }); } return data; } getColorMap(): { name: string; key: number; color: string }[] { return [ { name: 'Red', key: 0, color: 'red' }, { name: 'Orange', key: 1, color: 'orange' }, { name: 'Green', key: 2, color: 'green' }, { name: 'Light Blue', key: 3, color: 'lightblue' }, ]; } }
실행 시 FlexGrid의 모습은 다음과 같습니다
이 글이 여러분에게 도움이 되기를 바랍니다!
ComboBox에 대한 자세한 내용이 필요한 경우, Wijmo 를 참조해 보세요.
코드 예제는
지금 바로 Wijmo를 다운로드하여 직접 테스트해 보세요!
댓글목록
등록된 댓글이 없습니다.