Angular Tree Grid Summaries
La cuadrícula de la interfaz de usuario de Angular en Ignite UI for Angular tiene una característica de resúmenes que funciona en un nivel por columna como pie de página de grupo. Angular resúmenes de cuadrícula es una característica poderosa que permite al usuario ver la información de la columna en un contenedor separado con un conjunto predefinido de elementos de resumen predeterminados, según el tipo de datos dentro de la columna o mediante la implementación de una plantilla angular personalizada en la cuadrícula del árbol.
Ejemplo de resumen de resúmenes de cuadrícula de árbol de Angular
import { Component, ViewChild } from '@angular/core' ;
import { ColumnType, IgxTreeGridComponent, IgxColumnComponent, IgxCellTemplateDirective, IgxCellHeaderTemplateDirective, IgxIconComponent } from 'igniteui-angular' ;
import { ORDERS_DATA } from '../data/orders' ;
import { IgxPreventDocumentScrollDirective } from '../directives/prevent-scroll.directive' ;
import { NgIf, DatePipe } from '@angular/common' ;
@Component ({
selector : 'app-tree-grid-summary-sample' ,
styleUrls : ['./tree-grid-summary-sample.component.scss' ],
templateUrl : './tree-grid-summary-sample.component.html' ,
imports : [IgxTreeGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent, IgxCellTemplateDirective, IgxCellHeaderTemplateDirective, IgxIconComponent, NgIf, DatePipe]
})
export class TreeGridSummarySampleComponent {
@ViewChild ('treegrid1' , { read : IgxTreeGridComponent, static : true })
public grid1: IgxTreeGridComponent;
public data;
constructor ( ) {
this .data = ORDERS_DATA;
}
public toggleSummary (column: ColumnType ) {
column.hasSummary = !column.hasSummary;
}
}
ts コピー <div class ="grid__wrapper" >
<igx-tree-grid [igxPreventDocumentScroll ]="true" #treegrid1 [data ]="data" [autoGenerate ]="false" height ="700px" width ="100%"
primaryKey ="ID" foreignKey ="ParentID" >
<igx-column #col field ="ID" header ="Order ID" >
</igx-column >
<igx-column #col field ="Name" header ="Order Product" [hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val >
{{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > {{col.field}}</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Units" header ="Units" [filterable ]="false" [editable ]="true" dataType ="number"
[hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
{{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > Units</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="UnitPrice" header ="Unit Price" [filterable ]="false" [editable ]="true" dataType ="number"
[hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
${{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > Unit Price</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Price" header ="Price" [filterable ]="false" [editable ]="true" dataType ="number"
[hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
${{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > Price</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Delivered" header ="Delivered" [hasSummary ]="true" [dataType ]="'boolean'" >
<ng-template igxCell let-cell ="cell" let-val >
<img *ngIf ="val" src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/active.png" title ="Delivered" alt ="Delivered" />
<img *ngIf ="!val" src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/expired.png" title ="Undelivered" alt ="Undelivered" />
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > {{ col.field }}</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="OrderDate" header ="Order Date" [dataType ]="'date'" [hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
{{ val | date: 'MMM d, yyyy' }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > Order Date</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
</igx-tree-grid >
</div >
html コピー :host {
::ng-deep {
.grid-controls {
display: flex;
flex-flow : column nowrap;
justify-content : space-between;
margin : 0 16px 24px ;
igx-switch {
margin-top : 24px ;
}
}
.header {
height : 100% ;
}
.igx-grid__th .title {
width : 100% ;
cursor : auto;
}
}
}
.grid__wrapper {
margin : 0 16px ;
padding-top : 16px ;
}
@media screen and (max-width : 677px ){
[class*=header-icon] {
padding-bottom : 17px ;
padding-top : 17px ;
font-size : 1.4em ;
width : 1.1em ;
height : 1.1em ;
float : right;
}
[class*=text] {
float :left ;
white-space : nowrap;
overflow : hidden;
text-overflow : ellipsis;
width : 50% ;
}
}
@media screen and (min-width : 677px ){
[class*=header-icon] {
padding-top : 17px ;
font-size : 1.4em ;
width : 1.1em ;
height : 1.1em ;
float : right;
}
[class*=text] {
float :left ;
white-space : nowrap;
overflow : hidden;
text-overflow : ellipsis;
width : 50% ;
}
}
@media screen and (min-width : 992px ){
[class*=header-icon] {
padding-top : 17px ;
font-size : 1.4em ;
width : 1.1em ;
height : 1.1em ;
float : right;
margin-right : 10px ;
cursor : pointer;
}
[class*=text] {
float :left ;
white-space : nowrap;
width : 50% ;
cursor : auto;
}
}
scss コピー
¿Te gusta esta muestra? Obtenga acceso a nuestro kit de herramientas de Ignite UI for Angular completo y comience a crear sus propias aplicaciones en minutos. Descárgalo gratis.
El resumen de la columna es una función de todos los valores de la columna ; a menos que se aplique un filtrado, el resumen de la columna será función de los valores de los resultados filtrados.
Los resúmenes de cuadrícula de árbol también se pueden habilitar a nivel de columna en Ignite UI for Angular, lo que significa que solo puede activarlo para las columnas que necesite. Los resúmenes de cuadrícula de árbol le proporcionan un conjunto predefinido de resúmenes predeterminados, en función del tipo de datos de la columna, para que pueda ahorrar algo de tiempo:
Para string
y boolean
data types
, está disponible la siguiente función:
Para los tipos de datos number
, currency
y percent
, están disponibles las siguientes funciones:
contar
mín.
máximo
promedio
suma
Para el tipo de datos date
, están disponibles las siguientes funciones:
contar
más temprano
el último
Todos los tipos de datos de columna disponibles se pueden encontrar en el tema oficial Tipos de columna .
Los resúmenes de Tree Grid se habilitan por columna estableciendo la propiedad hasSummary
en true
. También es importante tener en cuenta que los resúmenes de cada columna se resuelven según el tipo de datos de la columna. En igx-tree-grid
el tipo de datos de columna predeterminado es string
, por lo que si desea resúmenes específicos number
o date
, debe especificar la propiedad dataType
como number
o date
. Tenga en cuenta que los valores de resumen se mostrarán localizados, según la locale
de la cuadrícula y la columna pipeArgs
.
<igx-tree-grid #grid1 [data ]="data" [autoGenerate ]="false" height ="800px" width ="800px" (columnInit )="initColumn($event)" >
<igx-column field ="ID" header ="Order ID" width ="200px" [sortable ]="true" > </igx-column >
<igx-column field ="Name" header ="Order Product" width ="200px" [sortable ]="true" [hasSummary ]="true" > </igx-column >
<igx-column field ="Units" width ="200px" [editable ]="true" [dataType ]="'number'" [hasSummary ]="true" > </igx-column >
</igx-tree-grid >
html
La otra forma de habilitar/deshabilitar resúmenes para una columna específica o una lista de columnas es usar el método público enableSummaries
/ disableSummaries
del igx-tree-grid .
<igx-tree-grid #grid1 [data ]="data" [autoGenerate ]="false" height ="800px" width ="800px" (columnInit )="initColumn($event)" >
<igx-column field ="ID" header ="Order ID" width ="200px" [sortable ]="true" > </igx-column >
<igx-column field ="Name" header ="Order Product" width ="200px" [sortable ]="true" [hasSummary ]="true" > </igx-column >
<igx-column field ="Units" width ="200px" [editable ]="true" [dataType ]="'number'" [hasSummary ]="false" > </igx-column >
</igx-tree-grid >
<button (click )="enableSummary()" > Enable Summary</button >
<button (click )="disableSummary()" > Disable Summary </button >
html
public enableSummary ( ) {
this .grid1.enableSummaries([
{fieldName : 'Units' , customSummary : this .mySummary},
{fieldName : 'ID' }
]);
}
public disableSummary ( ) {
this .grid1.disableSummaries('Name' );
}
typescript
Resúmenes de cuadrícula de árbol personalizados
Si estas funciones no cumplen con sus requisitos, puede proporcionar un resumen personalizado para las columnas específicas. Para lograr esto, debe anular una de las clases base IgxSummaryOperand
, IgxNumberSummaryOperand
o IgxDateSummaryOperand
según el tipo de datos de la columna y sus necesidades. De esta manera puede redefinir la función existente o puede agregar nuevas funciones. La clase IgxSummaryOperand
proporciona la implementación predeterminada solo para el método count
. IgxNumberSummaryOperand
extiende IgxSummaryOperand
y proporciona implementación para min
, max
, sum
y average
. IgxDateSummaryOperand
amplía IgxSummaryOperand
y, además, le ofrece las versiones earliest
y latest
.
import { IgxSummaryResult, IgxSummaryOperand, IgxNumberSummaryOperand, IgxDateSummaryOperand } from 'igniteui-angular' ;
class MySummary extends IgxNumberSummaryOperand {
constructor ( ) {
super ();
}
operate(data?: any []): IgxSummaryResult[] {
const result = super .operate(data);
result.push({
key : 'test' ,
label : 'Test' ,
summaryResult : data.filter(rec => rec > 10 && rec < 30 ).length
});
return result;
}
}
typescript
Como se ve en los ejemplos, las clases base exponen el método operate
, por lo que puede elegir obtener todos los resúmenes predeterminados y modificar el resultado, o calcular resultados resumidos completamente nuevos. El método devuelve una lista de IgxSummaryResult
.
interface IgxSummaryResult {
key : string ;
label: string ;
summaryResult: any ;
}
typescript
y tomar parámetros opcionales para calcular los resúmenes. Consulte Resúmenes personalizados, que acceden a toda la sección de datos a continuación.
Para calcular correctamente la altura de la fila de resumen, Tree Grid necesita que el método operate
devuelva siempre una matriz de IgxSummaryResult
con la longitud adecuada incluso cuando los datos están vacíos.
Y ahora agreguemos nuestro resumen personalizado a la columna UnitPrice
. Lo lograremos estableciendo la propiedad summaries
en la clase que creamos a continuación.
<igx-tree-grid #grid1 [data ]="data" [autoGenerate ]="false" height ="800px" width ="800px" (columnInit )="initColumn($event)" >
<igx-column field ="ID" header ="Order ID" width ="200px" [sortable ]="true" > </igx-column >
<igx-column field ="Name" header ="Order Product" width ="200px" [sortable ]="true" [hasSummary ]="true" > </igx-column >
<igx-column field ="Units" [dataType ]="'number'" width ="200px" [editable ]="true" [hasSummary ]="true" [summaries ]="mySummary" > </igx-column >
<igx-column field ="UnitPrice" header ="Unit Price" width ="200px" [dataType ]="'number'" [dataType ]="'currency'" [hasSummary ]="true" > </igx-column >
</igx-tree-grid >
html
...
export class GridComponent implements OnInit {
mySummary = MySummary;
....
}
typescript
Resúmenes personalizados, que acceden a todos los datos
Ahora puede acceder a todos los datos de Tree Grid dentro del resumen de columnas personalizado. Se introducen dos parámetros opcionales adicionales en el método operate
IgxSummaryOperand. Como puede ver en el fragmento de código a continuación, el método de operación tiene los siguientes tres parámetros:
columnData: le proporciona una matriz que contiene los valores solo para la columna actual
allGridData: le brinda toda la fuente de datos de la cuadrícula
fieldName - campo de columna actual
class MySummary extends IgxNumberSummaryOperand {
constructor ( ) {
super ();
}
operate(columnData: any [], allGridData = [], fieldName?): IgxSummaryResult[] {
const result = super .operate(allData.map(r => r[fieldName]));
result.push({ key : 'test' , label : 'Total Undelivered' , summaryResult : allData.filter((rec ) => rec.Discontinued).length });
return result;
}
}
typescript
import { Component, OnInit, ViewChild } from '@angular/core' ;
import { IgxSummaryOperand, IgxSummaryResult, IgxTreeGridComponent, IgxColumnComponent } from 'igniteui-angular' ;
import { generateEmployeeFlatData } from '../data/employees-flat' ;
import { IgxPreventDocumentScrollDirective } from '../../directives/prevent-scroll.directive' ;
class PTOSummary {
public operate(data?: any [], allData = [], fieldName = '' ): IgxSummaryResult[] {
const result = [];
result.push({
key : 'totalOnPTO' , label : 'Employees On PTO' ,
summaryResult : IgxSummaryOperand.count(allData.filter((rec ) => rec['OnPTO' ]).map(r => r[fieldName]))
});
result.push({
key : 'devs' , label : 'Developers' ,
summaryResult : IgxSummaryOperand.count(
allData.filter((rec ) => rec[fieldName].includes('Developer' ) && rec['OnPTO' ]).map(r => r[fieldName]))
});
result.push({
key : 'tl' , label : 'Team Leads' ,
summaryResult : IgxSummaryOperand.count(
allData.filter((rec ) => rec[fieldName].includes('Team Lead' ) && rec['OnPTO' ]).map(r => r[fieldName]))
});
result.push({
key : 'managers' , label : 'Managers/Directors' ,
summaryResult : IgxSummaryOperand.count(
allData.filter((rec ) =>
(rec[fieldName].includes('Manager' ) || rec[fieldName].includes('Director' )) && rec['OnPTO' ])
.map(r => r[fieldName]))
});
result.push({
key : 'ceo' , label : 'CEO/President' ,
summaryResult : IgxSummaryOperand.count(
allData.filter((rec ) =>
(rec[fieldName].includes('CEO' ) || rec[fieldName].includes('President' )) && rec['OnPTO' ])
.map(r => r[fieldName]))
});
return result;
}
}
@Component ({
selector : 'app-treegrid-all-data-summary-sample' ,
styleUrls : ['./treegrid-allData-summary.component.scss' ],
templateUrl : './treegrid-allData-summary.component.html' ,
imports : [IgxTreeGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent]
})
export class TreeGridAllDataSummaryComponent implements OnInit {
@ViewChild ('treegrid1' , { read : IgxTreeGridComponent, static : true })
public grid1: IgxTreeGridComponent;
public data;
public d;
public ptoSummary = PTOSummary;
constructor ( ) { }
public ngOnInit ( ) {
this .data = generateEmployeeFlatData();
this .data.forEach(rec => rec.Title = rec.Title.includes('Localiza' ) ? 'Software Developer' : rec.Title);
}
}
ts コピー <div class ="grid__wrapper" >
<div class ="sample-wrapper" >
<igx-tree-grid [igxPreventDocumentScroll ]="true" #treeGrid [data ]="data" cellSelection ="single" primaryKey ="ID"
foreignKey ="ParentID" height ="620px" width ="100%" >
<igx-column field ="Name" > </igx-column >
<igx-column field ="Age" width ="15%" > </igx-column >
<igx-column field ="Title" [hasSummary ]="true" [summaries ]="ptoSummary" > </igx-column >
<igx-column field ="HireDate" [dataType ]="'date'" [hasSummary ]="true" > </igx-column >
<igx-column field ="OnPTO" width ="15%" [dataType ]="'boolean'" [editable ]="true" [hasSummary ]="true" > </igx-column >
</igx-tree-grid >
</div >
</div >
html コピー .grid__wrapper {
--ig-size: var(--ig-size-small);
padding : 16px ;
}
scss コピー
Plantilla de resumen
igxSummary
apunta al resumen de la columna proporcionando como contexto los resultados del resumen de la columna.
<igx-column ... [hasSummary ]="true" >
<ng-template igxSummary let-summaryResults >
<span > My custom summary template</span >
<span > {{ summaryResults[0].label }} - {{ summaryResults[0].summaryResult }}</span >
</ng-template >
</igx-column >
html
Cuando se define un resumen predeterminado, la altura del área de resumen se calcula por diseño en función de la columna con el mayor número de resúmenes y el tamaño de la cuadrícula. Use la propiedad de entrada summaryRowHeight para invalidar el valor predeterminado. Como argumento, espera un valor numérico y, al establecer un valor falso, se activará el comportamiento de tamaño predeterminado del pie de página de la cuadrícula.
La plantilla de resumen de columna se puede definir a través de API estableciendo la propiedad SummaryTemplate de la columna en el TemplateRef requerido.
import { Component, HostBinding, OnInit } from '@angular/core' ;
import { IgxSummaryOperand, IgxSummaryResult, IgxInputGroupComponent, IgxLabelDirective, IgxInputDirective, IgxSwitchComponent, IgxButtonGroupComponent, IgxTreeGridComponent, IgxColumnComponent, IgxSummaryTemplateDirective } from 'igniteui-angular' ;
import { generateEmployeeFlatData } from '../data/employees-flat' ;
import { FormsModule } from '@angular/forms' ;
import { IgxPreventDocumentScrollDirective } from '../../directives/prevent-scroll.directive' ;
class PTOSummary {
public operate(data?: any [], allData = [], fieldName = '' ): IgxSummaryResult[] {
const result = [];
result.push({
key : 'totalOnPTO' , label : 'Employees On PTO' ,
summaryResult : IgxSummaryOperand.count(allData.filter((rec ) => rec['OnPTO' ]).map(r => r[fieldName]))
});
result.push({
key : 'devs' , label : 'Developers' ,
summaryResult : IgxSummaryOperand.count(
allData.filter((rec ) => rec[fieldName].includes('Developer' ) && rec['OnPTO' ]).map(r => r[fieldName]))
});
result.push({
key : 'tl' , label : 'Team Leads' ,
summaryResult : IgxSummaryOperand.count(
allData.filter((rec ) => rec[fieldName].includes('Team Lead' ) && rec['OnPTO' ]).map(r => r[fieldName]))
});
result.push({
key : 'managers' , label : 'Managers/Directors' ,
summaryResult : IgxSummaryOperand.count(
allData.filter((rec ) =>
(rec[fieldName].includes('Manager' ) || rec[fieldName].includes('Director' )) && rec['OnPTO' ])
.map(r => r[fieldName]))
});
result.push({
key : 'ceo' , label : 'CEO/President' ,
summaryResult : IgxSummaryOperand.count(
allData.filter((rec ) =>
(rec[fieldName].includes('CEO' ) || rec[fieldName].includes('President' )) && rec['OnPTO' ])
.map(r => r[fieldName]))
});
return result;
}
}
@Component ({
selector : 'app-treegrid-summary-template' ,
styleUrls : ['./treegrid-summary-template.component.scss' ],
templateUrl : './treegrid-summary-template.component.html' ,
imports : [IgxInputGroupComponent, IgxLabelDirective, FormsModule, IgxInputDirective, IgxSwitchComponent, IgxButtonGroupComponent, IgxTreeGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent, IgxSummaryTemplateDirective]
})
export class TreeGridSummaryTemplateComponent implements OnInit {
public data;
public d;
public ptoSummary = PTOSummary;
public summaryHeight = 150 ;
public size = 'medium' ;
public sizes;
public hasSummary = true ;
constructor ( ) { }
public ngOnInit(): void {
this .data = generateEmployeeFlatData();
this .data.forEach(rec => rec.Title = rec.Title.includes('Localiza' ) ? 'Software Developer' : rec.Title);
this .sizes = [
{ label : 'small' , selected : this .size === 'small' , togglable : true },
{ label : 'medium' , selected : this .size === 'medium' , togglable : true },
{ label : 'large' , selected : this .size === 'large' , togglable : true }
];
}
@HostBinding ('style.--ig-size' )
protected get sizeStyle () {
return `var(--ig-size-${this .size} )` ;
}
public selectSize(event): void {
this .size = this .sizes[event.index].label;
}
}
ts コピー <div class ="sample__wrapper" >
<div class ="controls-wrapper" >
<igx-input-group >
<label igxLabel for ="height" > Summary Row Height</label >
<input igxInput id ="height" name ="height" type ="number" [(ngModel )]="summaryHeight" >
</igx-input-group >
<igx-switch [(ngModel )]="hasSummary" > Toggle Summaries</igx-switch >
<igx-buttongroup [values ]="sizes" (selected )="selectSize($event)" > </igx-buttongroup >
</div >
<igx-tree-grid [igxPreventDocumentScroll ]="true" #treeGrid [data ]="data" cellSelection ="single" primaryKey ="ID"
foreignKey ="ParentID" height ="520px" width ="100%" [summaryRowHeight ]="summaryHeight" >
<igx-column field ="Name" > </igx-column >
<igx-column field ="Age" dataType ="number" width ="15%" [hasSummary ]="hasSummary" >
<ng-template igxSummary let-summaryResults >
<div class ="summary-temp" >
<span > <strong > {{ summaryResults[0].label }}</strong > <span > {{ summaryResults[0].summaryResult }}</span > </span >
<span > <strong > {{ summaryResults[1].label }}</strong > <span > {{ summaryResults[1].summaryResult }}</span > </span >
<span > <strong > {{ summaryResults[2].label }}</strong > <span > {{ summaryResults[2].summaryResult }}</span > </span >
<span > <strong > {{ summaryResults[3].label }}</strong > <span > {{ summaryResults[3].summaryResult }}</span > </span >
</div >
</ng-template >
</igx-column >
<igx-column field ="Title" [hasSummary ]="hasSummary" [summaries ]="ptoSummary" > </igx-column >
<igx-column field ="HireDate" [dataType ]="'date'" > </igx-column >
<igx-column field ="OnPTO" width ="15%" [dataType ]="'boolean'" [editable ]="true" [hasSummary ]="hasSummary" >
</igx-column >
</igx-tree-grid >
</div >
html コピー .sample__wrapper {
display : flex;
flex-direction : column;
gap: 16px ;
padding : 16px ;
height : 100% ;
overflow-y : auto;
}
igx-buttongroup {
max-width : 450px ;
flex : 1 ;
}
.summary-temp {
display : flex;
flex-direction : column;
margin : 0 1px ;
font-size : 14px ;
line-height : 24px ;
height : 100% ;
overflow-y : auto;
overflow-x : hidden;
span {
display : flex;
flex-wrap : wrap;
align-items : center;
gap: 4px ;
justify-content : space-between;
color : hsla(var(--igx-gray-900 ));
span {
user-select: all;
max-width : 300px ;
padding-right : 8px ;
}
strong {
font-size : 12px ;
text-transform : uppercase;
min-width : 70px ;
justify-self: flex-start;
text-align : left;
color : var(--ig-secondary-600 );
user-select: none;
}
}
> * {
padding : 8px 0 ;
line-height : 18px ;
border-bottom : 1px dashed hsla(var(--igx-gray-400 ));
&:last-child {
border-bottom : none;
}
}
}
::-webkit-scrollbar {
width: 5px !important ;
height : 5px !important ;
}
.controls-wrapper {
display : flex;
align-items : center;
flex-direction : row;
gap: 16px ;
}
scss コピー
Desactivar resúmenes
La disabledSummaries
propiedad proporciona un control preciso por columna sobre la característica de resumen de cuadrícula Ignite UI for Angular. Esta propiedad permite a los usuarios personalizar los resúmenes que se muestran para cada columna de la cuadrícula, lo que garantiza que solo se muestren los datos más relevantes y significativos. Por ejemplo, puede excluir tipos de resumen específicos, por ejemplo ['count', 'min', 'max']
, especificando sus claves de resumen en una matriz.
Esta propiedad también se puede modificar dinámicamente en tiempo de ejecución a través del código, lo que proporciona flexibilidad para adaptar los resúmenes de la cuadrícula a los cambios en los estados de la aplicación o las acciones del usuario.
En los ejemplos siguientes se muestra cómo utilizar la disabledSummaries
propiedad para administrar resúmenes de diferentes columnas y excluir tipos de resumen predeterminados y personalizados específicos en la cuadrícula Ignite UI for Angular:
<igx-column
field ="Units"
header ="Units"
dataType ="number"
[hasSummary ]="true"
[summaries ]="unitsSummary"
[disabledSummaries ]="['uniqueCount', 'maxDifference']"
>
</igx-column >
<igx-column
field ="UnitPrice"
header ="Unit Price"
dataType ="number"
[hasSummary ]="true"
[disabledSummaries ]="['count', 'sum', 'average']"
>
</igx-column >
html
En el caso Units
de los resúmenes personalizados, como totalDelivered
y totalNotDelivered
se excluyen mediante la disabledSummaries
propiedad.
Para UnitPrice
, los resúmenes predeterminados como count
, sum
, y average
están deshabilitados, dejando otros como y min
max
activos.
En tiempo de ejecución, los resúmenes también se pueden deshabilitar dinámicamente mediante la disabledSummaries
propiedad. Por ejemplo, puede establecer o actualizar la propiedad en columnas específicas mediante programación para adaptar los resúmenes mostrados en función de las acciones del usuario o los cambios de estado de la aplicación.
De forma predeterminada, los resultados de resumen, producidos por los operandos de resumen integrados, se localizan y se formatean según la locale
de la cuadrícula y la columna pipeArgs
. Cuando se utilizan operandos personalizados, la locale
y pipeArgs
no se aplican. Si desea cambiar la apariencia predeterminada de los resultados del resumen, puede formatearlos usando la propiedad summaryFormatter
.
public dateSummaryFormat(summary: IgxSummaryResult, summaryOperand : IgxSummaryOperand): string {
const result = summary.summaryResult;
if (summaryOperand instanceof IgxDateSummaryOperand && summary.key !== 'count'
&& result !== null && result !== undefined ) {
const pipe = new DatePipe('en-US' );
return pipe.transform(result,'MMM YYYY' );
}
return result;
}
typescript
<igx-column ... [summaryFormatter ]="dateSummaryFormat" > </igx-column >
html
import { DatePipe, NgIf } from '@angular/common' ;
import { Component, OnInit, ViewChild } from '@angular/core' ;
import { IgxDateSummaryOperand, IgxSummaryResult, IgxSummaryOperand, IgxTreeGridComponent, IgxColumnComponent, IgxCellTemplateDirective } from 'igniteui-angular' ;
import { ORDERS_DATA } from '../data/orders' ;
import { IgxPreventDocumentScrollDirective } from '../directives/prevent-scroll.directive' ;
@Component ({
selector : 'app-tree-grid-summary-formatter' ,
styleUrls : ['./tree-grid-summary-formatter.component.scss' ],
templateUrl : 'tree-grid-summary-formatter.component.html' ,
imports : [IgxTreeGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent, IgxCellTemplateDirective, NgIf]
})
export class TreeGridSummaryFormatterComponent implements OnInit {
@ViewChild ('treegrid1' , { read : IgxTreeGridComponent, static : true })
public treegrid1: IgxTreeGridComponent;
public data: any [];
public ngOnInit(): void {
this .data = ORDERS_DATA;
}
public dateSummaryFormat(summary: IgxSummaryResult, summaryOperand : IgxSummaryOperand): string {
const result = summary.summaryResult;
if (summaryOperand instanceof IgxDateSummaryOperand && summary.key !== 'count'
&& result !== null && result !== undefined ) {
const pipe = new DatePipe('en-US' );
return pipe.transform(result, 'MMM YYYY' );
}
return result;
}
}
ts コピー <div class ="grid__wrapper" >
<igx-tree-grid [igxPreventDocumentScroll ]="true" #treegrid1 [data ]="data" [autoGenerate ]="false" height ="600px" width ="100%"
[allowFiltering ]="true" filterMode ="excelStyleFilter"
primaryKey ="ID" foreignKey ="ParentID" >
<igx-column field ="ID" header ="Order ID" [sortable ]="true" [disableHiding ]="true" >
</igx-column >
<igx-column field ="Name" header ="Order Products" [sortable ]="true" [disableHiding ]="true" >
</igx-column >
<igx-column field ="Category" header ="Product Category" [sortable ]="true" [disableHiding ]="true" >
</igx-column >
<igx-column field ="Units" header ="Units" dataType ="string" [sortable ]="true" [disableHiding ]="true" >
</igx-column >
<igx-column field ="UnitPrice" header ="Unit Price" dataType ="string" [sortable ]="true" [disableHiding ]="true" >
</igx-column >
<igx-column field ="Price" header ="Total" dataType ="string" [sortable ]="true" [disableHiding ]="true" >
</igx-column >
<igx-column field ="OrderDate" header ="Order Date" [dataType ]="'date'" [sortable ]="true" [disableHiding ]="true"
[hasSummary ]="true" [summaryFormatter ]="dateSummaryFormat" >
</igx-column >
<igx-column field ="Delivered" header ="Delivered" [dataType ]="'boolean'" [sortable ]="true" [disableHiding ]="true" >
<ng-template igxCell let-cell ="cell" let-val >
<img *ngIf ="val" src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/active.png" title ="Delivered" alt ="Delivered" />
<img *ngIf ="!val" src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/expired.png" title ="Undelivered" alt ="Undelivered" />
</ng-template >
</igx-column >
</igx-tree-grid >
</div >
html コピー .grid__wrapper {
margin : 16px ;
}
scss コピー
Resúmenes infantiles
Tree Grid admite resúmenes separados para los nodos raíz y para cada nivel de nodo secundario anidado. Los resúmenes que se muestran se pueden configurar mediante la propiedad summaryCalculationMode
. Los resúmenes de nivel secundario se pueden mostrar antes o después de los nodos secundarios utilizando la propiedad summaryPosition
. Junto con estas dos propiedades, IgxTreeGrid expone una propiedad showSummaryOnCollapse
que le permite determinar si la fila de resumen permanece visible cuando el nodo principal al que hace referencia está colapsado.
Los valores disponibles de la propiedad summaryCalculationMode
son:
rootLevelOnly: los resúmenes se calculan solo para los nodos del nivel raíz.
childLevelsOnly: los resúmenes se calculan solo para los niveles secundarios.
rootAndChildLevels: los resúmenes se calculan tanto para el nivel raíz como para el nivel secundario. Este es el valor predeterminado.
Los valores disponibles de la propiedad summaryPosition
son:
arriba: la fila de resumen aparece antes de la lista de filas secundarias.
abajo: la fila de resumen aparece después de la lista de filas secundarias. Este es el valor predeterminado.
La propiedad showSummaryOnCollapse
es booleana. Su valor predeterminado está establecido en false , lo que significa que la fila de resumen se ocultará cuando se contraiga la fila principal. Si la propiedad se establece en verdadero, la fila de resumen permanece visible cuando se contrae la fila principal.
La propiedad summaryPosition
se aplica solo a los resúmenes de nivel secundario. Los resúmenes del nivel raíz siempre aparecen fijos en la parte inferior del Tree Grid.
import { Component, OnInit, ViewChild } from '@angular/core' ;
import { DefaultSortingStrategy, GridSummaryCalculationMode, GridSummaryPosition, IgxNumberSummaryOperand, IgxSummaryOperand, IgxSummaryResult, IgxTreeGridComponent, ISortingExpression, SortingDirection, IgxButtonGroupComponent, IgxSwitchComponent, IgxColumnComponent, IgxCellTemplateDirective } from 'igniteui-angular' ;
import { ORDERS_DATA } from '../data/orders' ;
import { IgxPreventDocumentScrollDirective } from '../directives/prevent-scroll.directive' ;
import { NgIf } from '@angular/common' ;
class AvgSummary {
public operate(data?: any []): IgxSummaryResult[] {
const result = [];
const avg = IgxNumberSummaryOperand.average(data);
result.push({
key : 'avg' ,
label : 'Average' ,
summaryResult : data.length ? '$' + avg.toFixed(2 ) : ''
});
return result;
}
}
@Component ({
selector : 'app-tree-grid-summary2-sample' ,
styleUrls : ['./tree-grid-summary2-sample.component.scss' ],
templateUrl : './tree-grid-summary2-sample.component.html' ,
imports : [IgxButtonGroupComponent, IgxSwitchComponent, IgxTreeGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent, IgxCellTemplateDirective, NgIf]
})
export class TreeGridSummary2SampleComponent implements OnInit {
@ViewChild ('treegrid1' , { read : IgxTreeGridComponent, static : true })
public grid1: IgxTreeGridComponent;
public data;
public expr: ISortingExpression[];
public avgSummary = AvgSummary;
public summaryPositions;
public summaryPosition: GridSummaryPosition = GridSummaryPosition.bottom;
public summaryCalcModes;
public summaryCalculationMode: GridSummaryCalculationMode = GridSummaryCalculationMode.rootAndChildLevels;
constructor ( ) {
this .data = ORDERS_DATA;
this .expr = [
{
dir : SortingDirection.Asc,
fieldName : 'ShipCountry' ,
ignoreCase : false ,
strategy : DefaultSortingStrategy.instance()
}
];
this .summaryPositions = [
{
label : GridSummaryPosition.top,
selected : this .summaryPosition === GridSummaryPosition.top,
togglable : true
},
{
label : GridSummaryPosition.bottom,
selected : this .summaryPosition === GridSummaryPosition.bottom,
togglable : true
}
];
this .summaryCalcModes = [
{
label : 'Root Level Only' ,
selected : this .summaryCalculationMode === GridSummaryCalculationMode.rootLevelOnly,
togglable : true ,
value : GridSummaryCalculationMode.rootLevelOnly
},
{
label : 'Child Levels Only' ,
selected : this .summaryCalculationMode === GridSummaryCalculationMode.childLevelsOnly,
togglable : true ,
value : GridSummaryCalculationMode.childLevelsOnly
},
{
label : 'Root And Child Levels' ,
selected : this .summaryCalculationMode === GridSummaryCalculationMode.rootAndChildLevels,
togglable : true ,
value : GridSummaryCalculationMode.rootAndChildLevels
}
];
}
public ngOnInit ( ) {
this .grid1.sortingExpressions = [
{ dir : SortingDirection.Desc, fieldName : 'ID' ,
ignoreCase : true , strategy : DefaultSortingStrategy.instance() }
];
}
public selectSummaryPosition (event ) {
this .summaryPosition = this .summaryPositions[event.index].label;
this .grid1.summaryPosition = this .summaryPosition;
}
public selectSummaryCalcMode (event ) {
this .summaryCalculationMode = this .summaryCalcModes[event.index].value;
this .grid1.summaryCalculationMode = this .summaryCalculationMode;
}
public toggle (event ) {
this .grid1.showSummaryOnCollapse = !this .grid1.showSummaryOnCollapse;
}
public formatCurrency (value: number ) {
return '$' + value.toFixed(2 );
}
}
ts コピー <div class ="summary-chooser" >
<igx-buttongroup [values ]="summaryCalcModes" (selected )="selectSummaryCalcMode($event)" > </igx-buttongroup >
</div >
<div class ="summary-chooser" >
<igx-buttongroup [values ]="summaryPositions" (selected )="selectSummaryPosition($event)" > </igx-buttongroup >
</div >
<div class ="summary-chooser" >
<igx-switch labelPosition ="before" [checked ]='treegrid1.showSummaryOnCollapse' (change )='toggle($event)' > Show summary row when group row is collapsed:</igx-switch >
</div >
<igx-tree-grid [igxPreventDocumentScroll ]="true" #treegrid1 [data ]="data" [autoGenerate ]="false" height ="500px" width ="100%"
primaryKey ="ID" foreignKey ="ParentID" >
<igx-column #col field ="ID" header ="Order ID" [sortable ]="true" >
</igx-column >
<igx-column #col field ="Name" header ="Order Product" [hasSummary ]="true" >
</igx-column >
<igx-column #col field ="UnitPrice" header ="Price" [formatter ]="formatCurrency" [filterable ]="false" [editable ]="true" dataType ="number"
[hasSummary ]="true" [summaries ]="avgSummary" >
</igx-column >
<igx-column #col field ="Delivered" header ="Delivered" [dataType ]="'boolean'" >
<ng-template igxCell let-cell ="cell" let-val >
<img *ngIf ="val" src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/active.png" title ="Delivered" alt ="Delivered" />
<img *ngIf ="!val" src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/expired.png" title ="Undelivered" alt ="Undelivered" />
</ng-template >
</igx-column >
<igx-column #col field ="OrderDate" header ="Order Date" [dataType ]="'date'" >
</igx-column >
</igx-tree-grid >
html コピー :host {
display : block;
padding : 8px ;
}
.summary-chooser {
margin-bottom : 16px ;
}
igx-buttongroup{
display : block;
width : 600px ;
}
scss コピー
Exportación de resúmenes
Existe una opción exportSummaries
en IgxExcelExporterOptions
que especifica si los datos exportados deben incluir los resúmenes del grid. El valor predeterminado exportSummaries
es falso .
IgxExcelExporterService
exportará los resúmenes predeterminados para todos los tipos de columnas como sus funciones de Excel equivalentes para que sigan funcionando correctamente cuando se modifique la hoja. Pruébelo usted mismo en el siguiente ejemplo:
import { Component, ViewChild } from '@angular/core' ;
import { ColumnType, IgxExcelExporterOptions, IgxExcelExporterService, IgxTreeGridComponent, IgxButtonDirective, IgxColumnComponent, IgxCellTemplateDirective, IgxCellHeaderTemplateDirective, IgxIconComponent } from 'igniteui-angular' ;
import { ORDERS_DATA } from '../data/orders' ;
import { IgxPreventDocumentScrollDirective } from '../directives/prevent-scroll.directive' ;
import { NgIf, DatePipe } from '@angular/common' ;
@Component ({
selector : 'app-tree-grid-summary-export' ,
styleUrls : ['./tree-grid-summary-export.component.scss' ],
templateUrl : './tree-grid-summary-export.component.html' ,
imports : [IgxButtonDirective, IgxTreeGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent, IgxCellTemplateDirective, IgxCellHeaderTemplateDirective, IgxIconComponent, NgIf, DatePipe]
})
export class TreeGridSummaryExportComponent {
@ViewChild ('tGrid' , { read : IgxTreeGridComponent, static : true })
public tGrid: IgxTreeGridComponent;
public data;
constructor (private excelExportService: IgxExcelExporterService ) {
this .data = ORDERS_DATA;
}
public toggleSummary (column: ColumnType ) {
column.hasSummary = !column.hasSummary;
}
public exportButtonHandler ( ) {
this .excelExportService.export(this .tGrid, new IgxExcelExporterOptions('ExportedFile' ));
}
}
ts コピー <div class ="grid__wrapper" >
<div class ="button-container" >
<button igxButton ="contained" (click )="exportButtonHandler()" > Export To Excel</button >
Press the button to export the Grid as a .xlsx file.
</div >
<igx-tree-grid [igxPreventDocumentScroll ]="true" #tGrid [data ]="data" [autoGenerate ]="false" height ="650px" width ="100%"
primaryKey ="ID" foreignKey ="ParentID" >
<igx-column #col field ="ID" header ="Order ID" >
</igx-column >
<igx-column #col field ="Name" header ="Order Product" [hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val >
{{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > {{col.field}}</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Category" header ="Category" [hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val >
{{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > {{col.field}}</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Units" header ="Units" [dataType ]="'number'" [hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val >
{{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > {{col.field}}</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="UnitPrice" header ="Unit Price" [filterable ]="false" [editable ]="true" dataType ="number"
[hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
${{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > Unit Price</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Price" header ="Price" [filterable ]="false" [editable ]="true" dataType ="number"
[hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
${{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > {{col.field}}</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Delivered" header ="Delivered" [hasSummary ]="true" [dataType ]="'boolean'" >
<ng-template igxCell let-cell ="cell" let-val >
<img *ngIf ="val" src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/active.png" title ="Delivered" alt ="Delivered" />
<img *ngIf ="!val" src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/expired.png" title ="Undelivered" alt ="Undelivered" />
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > {{ col.field }}</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="OrderDate" header ="Order Date" [dataType ]="'date'" [hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
{{ val | date: 'MMM d, yyyy' }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > Order Date</div >
<igx-icon class ="header-icon" style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
</igx-tree-grid >
</div >
html コピー :host {
::ng-deep {
.grid-controls {
display: flex;
flex-flow : column nowrap;
justify-content : space-between;
margin : 0 16px 24px ;
igx-switch {
margin-top : 24px ;
}
}
.header {
height : 100% ;
}
.igx-grid__th .title {
width : 100% ;
cursor : auto;
}
}
}
.grid__wrapper {
margin : 0 16px ;
padding-top : 16px ;
}
@media screen and (max-width : 677px ){
[class*=header-icon] {
padding-bottom : 17px ;
padding-top : 17px ;
font-size : 1.4em ;
width : 1.1em ;
height : 1.1em ;
float : right;
}
[class*=text] {
float :left ;
white-space : nowrap;
overflow : hidden;
text-overflow : ellipsis;
width : 50% ;
}
}
@media screen and (min-width : 677px ){
[class*=header-icon] {
padding-top : 17px ;
font-size : 1.4em ;
width : 1.1em ;
height : 1.1em ;
float : right;
}
[class*=text] {
float :left ;
white-space : nowrap;
overflow : hidden;
text-overflow : ellipsis;
width : 50% ;
}
}
@media screen and (min-width : 992px ){
[class*=header-icon] {
padding-top : 17px ;
font-size : 1.4em ;
width : 1.1em ;
height : 1.1em ;
float : right;
margin-right : 10px ;
cursor : pointer;
}
[class*=text] {
float :left ;
white-space : nowrap;
width : 50% ;
cursor : auto;
}
}
.button-container {
margin : 25px auto;
}
scss コピー
El archivo exportado incluye una columna oculta que contiene el nivel de cada DataRecord
en la hoja. Este nivel se utiliza en los resúmenes para filtrar las celdas que deben incluirse en la función de resumen.
En la siguiente tabla, puede encontrar la fórmula de Excel correspondiente a cada uno de los resúmenes predeterminados.
Tipo de datos
Función
Función Excel
string
, boolean
contar
="Contar: "&CONTAR.SI(inicio:fin, nivel de registro)
number
, currency
, percent
contar
="Contar: "&CONTAR.SI(inicio:fin, nivel de registro)
mín.
="Min: "&MIN(IF(inicio:fin=nivel de registro, inicio de rango:fin de rango))
máximo
="Máx: "&MAX(IF(inicio:fin=nivel de registro, inicio de rango:fin de rango))
promedio
="Promedio: "&PROMEDIOIF(inicio:fin, nivel de registro, inicio de rango:fin de rango)
suma
="Suma: "&SUMIF(inicio:fin, nivel de registro, inicio de rango:fin de rango)
date
contar
="Contar: "&CONTAR.SI(inicio:fin, nivel de registro)
más temprano
="Más temprano: "& TEXT(MIN(IF(start:end=recordLevel, rangeStart:rangeEnd)), formato)
el último
="Último: "&TEXT(MAX(IF(start:end=recordLevel, rangeStart:rangeEnd)), formato)
Limitaciones conocidas
Limitación
Descripción
Exportar resúmenes personalizados
Los resúmenes personalizados se exportarán como cadenas en lugar de funciones de Excel.
Exportar resúmenes con plantillas
Los resúmenes con plantilla no son compatibles y se exportarán como los predeterminados.
Navegación por teclado
Se puede navegar por las filas de resumen con las siguientes interacciones de teclado:
ARRIBA : navega una celda hacia arriba
ABAJO : navega una celda hacia abajo
IZQUIERDA : navega una celda hacia la izquierda
DERECHA : navega una celda hacia la derecha
CTRL + IZQUIERDA o INICIO : navega a la celda más a la izquierda
CTRL + DERECHA o FINAL : navega a la celda más a la derecha
Estilo
Para comenzar a diseñar el comportamiento de clasificación, necesitamos importar el archivo index
, donde se encuentran todas las funciones del tema y los mixins de componentes:
@use "igniteui-angular/theming" as *;
scss
Siguiendo el enfoque más simple, creamos un nuevo tema que extiende el grid-summary-theme
y acepta $background-color
, $focus-background-color
, $label-color
, $result-color
, $pinned-border-width
, Parámetros $pinned-border-style
y $pinned-border-color
.
$custom-theme : grid-summary-theme(
$background-color : #e0f3ff ,
$focus-background-color : rgba(#94d1f7 , .3 ),
$label-color : #e41c77 ,
$result-color : black,
$pinned-border-width : 2px ,
$pinned-border-style : dotted,
$pinned-border-color : #e41c77
);
scss
En lugar de codificar los valores de color como acabamos de hacer, podemos lograr una mayor flexibilidad en términos de colores mediante el uso de las palette
funciones y color
. Consulte el Palettes
tema para obtener orientación detallada sobre cómo usarlos.
El último paso es incluir el tema personalizado del componente:
@include css-vars($custom-theme );
scss
Si el componente utiliza una ViewEncapsulation Emulated
, es necesario penetrate
esta encapsulación usando::ng-deep
:
:host {
::ng-deep {
@include css-vars($custom-theme );
}
}
scss
Manifestación
import { Component, ViewChild } from '@angular/core' ;
import { ColumnType, IgxTreeGridComponent, IgxColumnComponent, IgxCellTemplateDirective, IgxCellHeaderTemplateDirective, IgxIconComponent } from 'igniteui-angular' ;
import { ORDERS_DATA } from '../data/orders' ;
import { IgxPreventDocumentScrollDirective } from '../directives/prevent-scroll.directive' ;
import { NgIf, DatePipe } from '@angular/common' ;
@Component ({
selector : 'app-tree-grid-summary-styling' ,
styleUrls : ['./tree-grid-summary-styling.component.scss' ],
templateUrl : './tree-grid-summary-styling.component.html' ,
imports : [IgxTreeGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent, IgxCellTemplateDirective, IgxCellHeaderTemplateDirective, IgxIconComponent, NgIf, DatePipe]
})
export class TreeGridSummaryStylingComponent {
@ViewChild ('treegrid1' , { read : IgxTreeGridComponent, static : true })
public grid1: IgxTreeGridComponent;
public data;
constructor ( ) {
this .data = ORDERS_DATA;
}
public toggleSummary (column: ColumnType ) {
column.hasSummary = !column.hasSummary;
}
}
ts コピー <div class ="grid__wrapper" >
<igx-tree-grid [igxPreventDocumentScroll ]="true" #treegrid1 [data ]="data" [autoGenerate ]="false" height ="600px" width ="100%"
primaryKey ="ID" foreignKey ="ParentID" >
<igx-column #col field ="ID" header ="Order ID" >
</igx-column >
<igx-column #col field ="Name" header ="Order Product" [hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val >
{{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > {{col.field}}</div >
<igx-icon style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" class ="header-icon" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Category" header ="Category" [hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val >
{{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > {{col.field}}</div >
<igx-icon style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" class ="header-icon" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Units" header ="Units" [filterable ]="false" [editable ]="true" dataType ="number"
[hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
{{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > Units</div >
<igx-icon style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" class ="header-icon" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="UnitPrice" header ="Unit Price" [filterable ]="false" [editable ]="true" dataType ="number"
[hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
${{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > Unit Price</div >
<igx-icon style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" class ="header-icon" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Price" header ="Price" [filterable ]="false" [editable ]="true" dataType ="number"
[hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
${{ val }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > Price</div >
<igx-icon style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" class ="header-icon" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="Delivered" header ="Delivered" [hasSummary ]="true" [dataType ]="'boolean'" >
<ng-template igxCell let-cell ="cell" let-val >
<img *ngIf ="val" src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/active.png" title ="Delivered" alt ="Delivered" />
<img *ngIf ="!val" src ="https://www.infragistics.com/angular-demos-lob/assets/images/grid/expired.png" title ="Undelivered" alt ="Undelivered" />
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > {{ col.field }}</div >
<igx-icon style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" class ="header-icon" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
<igx-column #col field ="OrderDate" header ="Order Date" [dataType ]="'date'" [hasSummary ]="true" >
<ng-template igxCell let-cell ="cell" let-val let-row >
{{ val | date: 'MMM d, yyyy' }}
</ng-template >
<ng-template igxHeader let-col >
<div class ="text" > Order Date</div >
<igx-icon style.color ="{{ col.hasSummary ? '#e41c77' : '' }}" class ="header-icon" (click )="toggleSummary(col)" > functions</igx-icon >
</ng-template >
</igx-column >
</igx-tree-grid >
</div >
html コピー @use "layout.scss" ;
@use "igniteui-angular/theming" as *;
$custom-theme : grid-summary-theme(
$background-color : #e0f3ff ,
$focus-background-color : rgba(#94d1f7 , .3 ),
$label-color : #e41c77 ,
$result-color : black,
$pinned-border-width : 2px ,
$pinned-border-style : dotted,
$pinned-border-color : #e41c77
);
:host {
::ng-deep {
@include css-vars($custom-theme );
}
}
scss コピー
Referencias de API
Recursos adicionales
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.