import { Component, Output, EventEmitter, QueryList, ContentChildren, AfterContentInit } from '@angular/core'; import { RowActionComponent } from '../RowAction/row-action.component'; /** * This component is responsible for showing all available actions at the end of each * row in a datatable. If `items` contains at least one enabled action, the `show_more_horiz` * icon button will be visible, otherwise it will be hidden. If `actionText` and `actionWhen` * are truthy, a mat button with `actionText` will be rendered. If `actionIcon` and `actionIconWhen` * are truthy, a mat icon button with `actionIcon` will be rendered. * * ``` * [ ACTION ] [ ICON ] [...] * |- [ enabledItems[0] ] * |- [ enabledItems[1] ] * |- [ enabledItems[2] ] * |- ... * ``` */ @Component({ selector: 'row-actions', templateUrl: './row-actions.component.html', styleUrls: ['./row-actions.component.scss'] }) export class RowActionsComponent implements AfterContentInit { @ContentChildren(RowActionComponent) actions!: QueryList; // parent components should set column width based on this size @Output() resize: EventEmitter = new EventEmitter(true); hasViewButton = false; hasIconButton = false; hasMoreButton = false; hasInitialized = false; elementCount = 0; constructor() { } ngAfterContentInit() { this.determineElementVisibility(); this.actions.forEach(action => action.visibilityChanges.subscribe( _ => this.determineElementVisibility() ) ); } determineElementVisibility(): void { const previousElementCount = this.elementCount; this.elementCount = 0; this.hasViewButton = false; this.hasIconButton = false; this.hasMoreButton = false; for (const action of this.actions.toArray()) { if (this.whenActive(action.when)) { switch (action.type) { case 'action': this.hasViewButton = true; this.elementCount++; break; case 'icon': this.hasIconButton = true; this.elementCount++; break; case 'option': if (!this.hasMoreButton) { this.hasMoreButton = true; this.elementCount++; } break; } } } if (!this.hasInitialized || this.elementCount !== previousElementCount) { this.hasInitialized = true; this.calculateWidth(); } } whenActive(when: boolean | undefined): boolean { return typeof when === 'undefined' || when === true; } calculateWidth() { let width = 17; if (this.hasViewButton) { width += 61; } if (this.hasIconButton) { width += 40; } if (this.hasMoreButton) { width += 40; } if (width === 17) { width += 83; } this.resize.emit(width); } }