src/app/core/entity-details/related-entities-with-summary/related-entities-with-summary.component.ts

Description

Load and display a list of related entities including a summary below the table.

Extends

RelatedEntitiesComponent<E>

Example

Metadata

Relationships

Index

Properties
Methods
Inputs
Outputs

Inputs

summaries
Type : { countProperty: string; groupBy?: string; total?: boolean; average?: boolean; }

Configuration of what numbers should be summarized below the table.

clickMode
Type : "popup" | "navigate" | "popup-details"
Default value : "popup"
Inherited from RelatedEntitiesComponent
columns
Type : ColumnConfig[]
Default value : []
Inherited from RelatedEntitiesComponent

Columns to be displayed in the table

dataSource
Type : DataSourceType
Inherited from RelatedEntitiesComponent
editable
Type : boolean
Default value : true
Inherited from RelatedEntitiesComponent
entity
Type : Entity
Inherited from RelatedEntitiesComponent

currently viewed/main entity for which related entities are displayed in this component

entityType
Type : string
Inherited from RelatedEntitiesComponent

entity type of the related entities to be displayed

filter
Type : DataFilter<E>
Inherited from RelatedEntitiesComponent

This filter is applied before displaying the data.

loaderMethod
Type : LoaderMethod
Inherited from RelatedEntitiesComponent

The special service or method to load data via an index or other special method.

property
Type : string | string[]
Inherited from RelatedEntitiesComponent

Property name of the related entities (type given in this.entityType) that holds the entity id to be matched with the id of the current main entity (given in this.entity). If not explicitly set, this will be inferred based on the defined relations between the entities.

manually setting this is only necessary if you have multiple properties referencing the same entity type and you want to list only records related to one of them. For example: if you set entityType = "Project" (to display a list of projects here) and the Project entities have a properties "participants" and "supervisors" both storing references to User entities, you can set property = "supervisors" to only list those projects where the current User is supervisors, not participant.

showInactive
Type : boolean | undefined
Default value : undefined
Inherited from RelatedEntitiesComponent

Whether inactive/archived records should be shown.

Outputs

showInactive
Type : boolean | undefined
Inherited from RelatedEntitiesComponent

Whether inactive/archived records should be shown.

Methods

createNewRecordFactory
createNewRecordFactory()
Inherited from RelatedEntitiesComponent
Returns : () => any
Protected getColumns
getColumns(value: ColumnConfig[] | undefined)
Inherited from RelatedEntitiesComponent
Parameters :
Name Type Optional
value ColumnConfig[] | undefined No
Returns : FormFieldConfig[]
Protected getDefaultColumns
getDefaultColumns()
Inherited from RelatedEntitiesComponent
Returns : FormFieldConfig[]
Protected getProperty
getProperty()
Inherited from RelatedEntitiesComponent

Auto-detect which properties of the related entity type reference the current entity. Returns dot-paths for nested references (e.g. "attendance.participant").

Returns : string | []
Protected initFilter
initFilter()
Inherited from RelatedEntitiesComponent
Returns : DataFilter<E>

Properties

recordsDataSource
Type : unknown
Default value : signal(new InMemoryDataSource<E>())
Inherited from RelatedEntitiesComponent

Ignore dataSource input and always use in-memory datasource because summaries need all records present

Protected Readonly summary
Type : unknown
Default value : computed(() => this.buildSummary())
Readonly _columns
Type : unknown
Default value : computed(() => { const entity = this.entity(); const rawCols = this.getColumns(this.columns()); if (!entity) return rawCols; return rawCols.map((column) => { if (typeof column.additional === "object" && column.additional !== null) { return { ...column, additional: { ...column.additional, relatedEntitiesParent: entity }, }; } return column; }); })
Inherited from RelatedEntitiesComponent
Readonly columnsToDisplay
Type : unknown
Default value : computed(() => this._columns() .filter((column) => { if (column?.hideFromTable) return false; const numericValue = ScreenSize[column?.visibleFrom]; if (numericValue === undefined) return true; return this.currentScreenSize() >= numericValue; }) .map((c) => c.id), )
Inherited from RelatedEntitiesComponent
Protected Readonly entityCtr
Type : unknown
Default value : computed<EntityConstructor<E> | undefined>( () => { const entityType = this.entityType(); if (!entityType) { return undefined; } return this.entityRegistry.get(entityType) as EntityConstructor<E>; }, )
Inherited from RelatedEntitiesComponent
Readonly filterObj
Type : unknown
Default value : signal<DataFilter<E>>({})
Inherited from RelatedEntitiesComponent
Protected filterService
Type : unknown
Default value : inject(FilterService)
Inherited from RelatedEntitiesComponent
Protected Readonly relationProperty
Type : unknown
Default value : computed<string | string[]>(() => { const entity = this.entity(); const entityCtr = this.entityCtr(); if (!entity || !entityCtr) { return []; } const resolvedProperty = this.property() ?? this.getProperty(); return typeof resolvedProperty === "string" ? this.resolvePropertyPath(resolvedProperty) : resolvedProperty.map((p) => this.resolvePropertyPath(p)); })
Inherited from RelatedEntitiesComponent
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  signal,
} from "@angular/core";
import { CustomFormLinkButtonComponent } from "app/features/public-form/custom-form-link-button/custom-form-link-button.component";
import { EntitiesTableComponent } from "../../common-components/entities-table/entities-table.component";
import { DynamicComponent } from "../../config/dynamic-components/dynamic-component.decorator";
import { Entity } from "../../entity/model/entity";
import { RelatedEntitiesComponent } from "../related-entities/related-entities.component";
import { InMemoryDataSource } from "#src/app/core/common-components/entities-table/data-source/in-memory-data-source";

/**
 * Load and display a list of related entities
 * including a summary below the table.
 */
@DynamicComponent("RelatedEntitiesWithSummary")
@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: "app-related-entities-with-summary",
  templateUrl: "./related-entities-with-summary.component.html",
  imports: [EntitiesTableComponent, CustomFormLinkButtonComponent],
})
export class RelatedEntitiesWithSummaryComponent<
  E extends Entity = Entity,
> extends RelatedEntitiesComponent<E> {
  /**
   * Configuration of what numbers should be summarized below the table.
   */
  summaries = input<{
    countProperty: string;
    groupBy?: string;
    total?: boolean;
    average?: boolean;
  }>();

  /** Ignore `dataSource` input and always use in-memory datasource because summaries need all records present */
  override recordsDataSource = signal(new InMemoryDataSource<E>());

  protected readonly summary = computed(() => this.buildSummary());

  private buildSummary() {
    const summaries = this.summaries();
    if (!summaries) {
      return { sum: "", avg: "" };
    }

    const summary = new Map<
      string | undefined,
      { count: number; sum: number }
    >();
    const filteredData = this.recordsDataSource().filteredRecords();

    filteredData.forEach((m) => {
      const amount = Number(m[summaries.countProperty]);
      let groupLabel: string | undefined;
      if (summaries.groupBy) {
        groupLabel = m[summaries.groupBy]?.label ?? m[summaries.groupBy];
      }

      summary.set(groupLabel, summary.get(groupLabel) || { count: 0, sum: 0 });
      summary.get(groupLabel).count++;
      summary.get(groupLabel).sum += amount;
    });

    let summarySum = "";
    let summaryAvg = "";

    if (summaries.total) {
      const summarySumArray = Array.from(
        summary.entries(),
        ([label, { sum }]) => `${label}: ${sum}`,
      );
      summarySum = summarySumArray.join(", ");
    }

    if (summaries.average) {
      const summaryAvgArray = Array.from(
        summary.entries(),
        ([label, { count, sum }]) => {
          const avg = parseFloat((sum / count).toFixed(2));
          return `${label}: ${avg}`;
        },
      );
      summaryAvg = summaryAvgArray.join(", ");
    }

    if (summary.size === 1 && summary.has(undefined)) {
      // display only single summary without group label (this also applies if no groupBy is given)
      summarySum = summarySum.replace("undefined: ", "");
      summaryAvg = summaryAvg.replace("undefined: ", "");
    }

    return { sum: summarySum, avg: summaryAvg };
  }
}
<app-entities-table
  [entityType]="entityCtr()!"
  [recordsDataSource]="recordsDataSource()"
  [filter]="filterObj()"
  [customColumns]="_columns()"
  [newRecordFactory]="createNewRecordFactory()"
></app-entities-table>

<div class="margin-top-large">
  @if (summary().sum) {
    <strong i18n>Total:</strong> {{ summary().sum }} <br />
  }
  @if (summary().avg) {
    <strong i18n>Average:</strong> {{ summary().avg }} <br />
  }
</div>

<app-custom-form-link-button
  [linkedEntity]="entity()"
  [formEntityType]="entityCtr()!"
>
</app-custom-form-link-button>
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""