[Feat] Permettere l'utilizzo del componente <it-table> con un approccio più dichiarativo
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 15/100
- Issue type
- Feature
- Clarity
- Needs clarification
- Activity status
- Active
- Tech stack
- angular, typescript
- Domain
- frontend
Research direction
The proposal is a wrapper component around <it-table> that uses content projection (TableCellDirective, ng-template[appTableCell]) and signals, with helpers in table.types.ts and table.utils.ts. Before any code, the maintainers need to decide the public API (headers, cell slots, expand support), which the issue does not settle. Done would mean an agreed API design and a discussion outcome, not a patch.
Written by the indexing model from the issue text.
Description
Esiste già una discussione sul tema che ti interessa, o su un tema simile?
- Ho verificato e non esiste
Versione della libreria
v20.3.0
Cosa
Al momento la definizione di una tabella BSI, sebbene esista il componente <it-table>, risulta comunque molto manuale. Condivido con voi un wrapper da me creato per farvi capire meglio cosa intendo con "approccio dichiarativo"
// table.component.ts
// Imports...
const EXPAND_COL = 'table-expand';
const EXPANDED_SLOT = 'expanded';
/**
* Projects cell content into the column matching the provided header key.
*/
@Directive({ selector: 'ng-template[appTableCell]' })
export class TableCellDirective {
readonly templateRef = inject(TemplateRef);
readonly key = input.required<string>({ alias: 'appTableCell' });
}
/**
* Wraps `<it-table>` with a simpler API and extended capabilities.
*/
@Component({
selector: 'app-table',
imports: [ItTableComponent, ItProgressBarComponent, ItButtonDirective, ItIconComponent, NgTemplateOutlet, TranslatePipe],
template: `
<ng-template
#defaultCell
let-value="value"
>
{{ value }}
</ng-template>
<it-table
class="my-table"
alignment="align-middle"
compact="true"
hover="true"
[attr.aria-busy]="loading()"
>
<ng-container thead>
<tr>
@for (header of internalHeaders(); track header.key) {
<th
[class]="header.class"
scope="col"
>
<span [class.visually-hidden]="header.isInternal">
{{ header.title }}
</span>
</th>
}
</tr>
</ng-container>
<ng-container tbody>
@if (loading() && !rows().length) {
@for (row of skeletonRows(); track row.id) {
<tr
class="placeholder-glow"
aria-hidden="true"
>
@for (header of internalHeaders(); track header.key) {
<td [class]="header.class">
@if (!header.isInternal) {
<span [class]="['placeholder', row.widthClass]"></span>
}
</td>
}
</tr>
}
} @else {
@if (loading()) {
<tr
class="my-table__progress"
aria-hidden="true"
>
<td
class="p-0 border-0"
[attr.colspan]="internalHeaders().length"
>
<it-progress-bar
[value]="0"
indeterminate="true"
/>
</td>
</tr>
}
@for (row of rows(); track $index) {
@let isExpanded = row.isExpandable && rowIsExpanded(row.item);
<tr
[class.opacity-50]="loading()"
[inert]="loading()"
>
@for (cell of row.cells; track cell.headerKey) {
@let template = cell.template ?? defaultCell;
@if (cell.kind === 'row-header') {
<th
[class]="cell.class"
scope="row"
>
<ng-container *ngTemplateOutlet="template; context: cell.context" />
</th>
} @else {
<td [class]="cell.class">
@switch (cell.kind) {
@case ('expand') {
@if (row.isExpandable) {
<button
class="my-table__expand btn dropdown-toggle"
type="button"
[attr.aria-label]="
'components.table.actions.' +
(isExpanded ? 'collapse-row' : 'expand-row') | translate
"
[attr.aria-expanded]="isExpanded"
(click)="toggleRow(row.item)"
>
<it-icon
svgClass="icon-expand"
name="expand"
/>
</button>
}
}
@default {
<ng-container *ngTemplateOutlet="template; context: cell.context" />
}
}
</td>
}
}
</tr>
@if (isExpanded && expandedTemplate(); as template) {
<ng-container *ngTemplateOutlet="template; context: { $implicit: row.item }" />
}
} @empty {
<tr class="my-table__empty no-hover">
<td
class="text-muted text-center"
[attr.colspan]="internalHeaders().length"
>
{{ 'data-display.empty' | translate }}
</td>
</tr>
}
}
</ng-container>
</it-table>
`,
styles: `
:host ::ng-deep .table {
margin: 0;
}
tr.no-hover {
--bs-table-hover-bg: initial;
}
td.fit-content {
width: 1px;
}
`,
})
export class TableComponent<T extends object = object> {
private readonly translateService = inject(TranslateService);
readonly headers = input.required<readonly TableHeader<T>[]>();
readonly items = input.required<readonly T[] | undefined>();
readonly loading = input(false, { transform: booleanAttribute });
readonly loadingRows = input(10, { transform: numberAttribute });
readonly showExpand = input<TableShowExpand<T>, TableShowExpand<T> | string>(false, {
transform: showExpandAttribute,
});
private readonly expanded = linkedSignal({
source: this.items,
computation: (): ReadonlySet<T> => new Set(),
});
protected readonly expandedTemplate = contentChild<TemplateRef<{ $implicit: T }>>(EXPANDED_SLOT);
private readonly cellTemplates = contentChildren(TableCellDirective);
private readonly cellTemplateMap = computed(
(): ReadonlyMap<string, TableCellTemplate<T>> =>
new Map(this.cellTemplates().map((dir) => [dir.key(), dir.templateRef])),
);
protected readonly internalHeaders = computed((): readonly InternalTableHeader<T>[] => {
const headers: InternalTableHeader<T>[] = [
{
key: EXPAND_COL,
title: this.translateService.instant('components.table.headers.expand'),
class: 'fit-content',
isInternal: true,
isHidden: !this.showExpand(),
},
...this.headers().map((header): InternalTableHeader<T> => ({
...header,
class: cx(header.align && `text-${header.align}`),
})),
];
return headers.filter((header) => !header.isHidden);
});
protected readonly rows = computed((): readonly TableRow<T>[] => {
const rowHeader = this.headers().at(0);
const items = this.items();
if (!rowHeader || !items) return [];
const headers = this.internalHeaders();
const templates = this.cellTemplateMap();
const showExpand = this.showExpand();
return items.map((item): TableRow<T> => ({
item,
isExpandable: typeof showExpand === 'function' ? showExpand(item) : showExpand,
cells: headers.map((header): TableCell<T> => ({
class: header.class,
headerKey: header.key,
template: templates.get(header.key),
context: { $implicit: item, value: resolveValue(header, item) },
kind: getKind(header.key, rowHeader.key),
})),
}));
});
protected readonly skeletonRows = computed(() =>
Array.from({ length: this.loadingRows() }).map((_, i) => ({
id: i,
widthClass: getRandomPlaceholderWidth(),
})),
);
protected rowIsExpanded(item: T): boolean {
return this.expanded().has(item);
}
protected toggleRow(item: T): void {
this.expanded.update((val) => {
const next = new Set(val);
if (next.has(item)) next.delete(item);
else next.add(item);
return next;
});
}
}
const MIN_COL = 4;
const MAX_COL = 11;
/**
* Returns a random Bootstrap column utility class for visually balanced placeholders.
*/
function getRandomPlaceholderWidth(): string {
return `col-${Math.floor(Math.random() * (MAX_COL - MIN_COL + 1)) + MIN_COL}`;
}
/**
* Joins CSS classes into a single `className`.
*/
function cx(...classes: readonly (string | false | undefined)[]): string | undefined {
return classes.filter((c): c is string => Boolean(c && c.trim())).join(' ') || undefined;
}
// table.types.ts
import { TemplateRef } from '@angular/core';
export interface TableHeader<T extends object = object> {
/**
* Unique column id, also used as the slot name for cell templates.
*/
readonly key: string;
readonly title: string;
/**
* Dot-notation property path or accessor function used to resolve the cell value.
*/
readonly value?: string | ((item: T) => unknown);
readonly align?: 'start' | 'center' | 'end';
}
export interface InternalTableHeader<T extends object> extends TableHeader<T> {
readonly class: string;
/**
* Marks injected utility columns.
*/
readonly isInternal?: boolean;
/**
* Prevents disabled utility columns from rendering.
*/
readonly isHidden?: boolean;
}
export interface TableRow<T> {
readonly item: T;
readonly cells: readonly TableCell<T>[];
readonly isExpandable: boolean;
}
export interface TableCell<T> {
readonly class?: string;
readonly headerKey: string;
readonly template?: TableCellTemplate<T>;
readonly context: TableCellContext<T>;
readonly kind: TableCellKind;
}
export interface TableCellContext<T> {
readonly $implicit: T;
readonly value: unknown;
}
export type TableCellTemplate<T> = TemplateRef<TableCellContext<T>>;
export type TableCellKind = 'expand' | 'row-header' | 'data';
export type TableShowExpand<T> = boolean | ((item: T) => boolean);
// table.utils.ts
import { booleanAttribute } from '@angular/core';
import { TableCellKind, TableHeader, TableShowExpand } from './table.types';
export function showExpandAttribute<T>(value: TableShowExpand<T> | string): TableShowExpand<T> {
return typeof value === 'function' ? value : booleanAttribute(value);
}
export function resolveValue<T extends object>(header: TableHeader<T>, item: T): unknown {
const { value } = header;
switch (typeof value) {
case 'string':
return get(item, value);
case 'function':
return value(item);
default:
return;
}
}
export function getKind(headerKey: string, rowHeaderKey: string): TableCellKind {
switch (headerKey) {
case EXPAND_COL:
return 'expand';
case rowHeaderKey:
return 'row-header';
default:
return 'data';
}
}
/**
* Gets the value at `path` of `object`.
*
* @param object The object to query.
* @param path The path of the property to get.
* @returns The resolved value.
*/
function get<T>(object: T, path: string): unknown {
if (!path) return;
return path.split('.').reduce<unknown>((acc, segment) => {
if (!acc || typeof acc !== 'object') return;
return Reflect.get(acc, segment);
}, object);
}
Perché
Per potenziare un pochino il componente tabella
Contesto
No response
Altro
Implementazione ispirata alla data table di Vuetify
- Dominant language
- TypeScript
- Stars
- 88
- Forks
- 47
- Avg merge
- 19h 31m
- Merged PRs (30d)
- 18
Getting set up
Starts the project's dev container in your browser, under your own GitHub account.
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from italia/design-angular-kit
-
Steppers: confirmedLabel usato anche come etichetta accessibile della spunta dei passi completatiOpen
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
italia/design-angular-kit#817 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
italia/design-angular-kit#813 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
italia/design-angular-kit#738 ·
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
italia/design-angular-kit#729 · 2 comments ·
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
italia/design-angular-kit#723 ·
Maintainers usually reply within 1 day
All issues in italia/design-angular-kit
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
melgarafael/DeskcommCRM#5614 · 1 comment ·
Maintainers usually reply within 1 day
-
documentation
Difficulty 1/5 Under an hour Newbie friendliness 76/100
slackapi/slack-health-score#253 ·
Maintainers usually reply within 1 day
-
feature needs triage site
Difficulty 2/5 1-3 hours Newbie friendliness 64/100
owid/owid-grapher#8019 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
simstudioai/sim#10710 ·
Maintainers usually reply within 1 day
-
via-triage
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
Maintainers usually reply within 1 day