1.1.4 • Published 9 months ago

@maspav/mgmt-ptl-shared v1.1.4

Weekly downloads
-
License
-
Repository
-
Last release
9 months ago

@maspav/mgmt-ptl-shared

Table of Contents

Introduction

The @maspav/mgmt-ptl-shared library is a shared module that provides a collection of reusable services, pipes, and directives for Angular applications. It includes components for user interface elements, custom pipes for data manipulation, and directives for enhancing DOM behavior.

Installation

To install the library, use npm:

npm i @maspav/mgmt-ptl-shared

Modules

  • The library exports the following modules (exported in the main module called MgmtPtlSharedModule):
    • MgmtPtlSharedModule: Main module exporting components, modules, directives, and pipes.
    • PerfectScrollbarModule: For custom scrollbar functionality.
    • NgxMaskModule: For input masking.
    • CommonModule: Provides common directives like ngIf and ngFor, as well as pipes like DatePipe and DecimalPipe. It is a module that is imported into feature modules to use Angular's common functionalities.
    • RouterModule: Provides navigation and routing capabilities in an Angular application. It enables defining routes, navigating between views, and managing route parameters
    • NgbModule: A module from the ng-bootstrap library that provides Bootstrap components and directives for Angular applications, such as modals, alerts, and pagination.
    • FormsModule: Supports template-driven forms in Angular, allowing for easy creation and management of forms using HTML templates with Angular's form directives.
    • ReactiveFormsModule: Provides support for reactive forms, allowing for more complex form handling and validation using a model-driven approach, with FormGroup, FormControl, and FormBuilder.
    • FeatherModule.pick(featherIcons): This module provides integration with Feather icons, allowing for the easy use of Feather icons in Angular applications. The pick method is used to select specific icons.
    • NgSelectModule: Provides the ng-select component, a versatile and customizable select dropdown with support for single and multiple selections, filtering, and remote data loading.
    • ClipboardModule: From the ngx-clipboard library, this module provides clipboard functionalities, including copying text to the clipboard programmatically within an Angular application.

Components

The library includes the following components (exported in the main module called MgmtPtlSharedModule except for AceEditorComponent):

  • PageUnderConstructionComponent: A component indicating that a page is under construction.
  • BulletComponent: Displays a bullet point.
  • ContentWrapperComponent: Wraps content with additional styling.
  • ContentHeaderComponent: Displays a header for content sections.
  • NoRecordsComponent: Displays a message when no records are available.
  • SpinnerComponent: A loading spinner component.
  • FormErrorsComponent: Displays form validation errors.
  • PaginationComponent: Adds pagination controls.
  • ModalWrapperComponent: Wraps content in a modal dialog.
  • ConfirmationModalComponent: A modal for confirmation dialogs.
  • StaffListComponent: Displays a list of staff members.
  • FiltersComponent, FilterButtonComponent, AdvancedFiltersComponent: Components for applying filters.
  • InstantExportButtonComponent, ExportComponent: Components for exporting data.
  • MonthPickerComponent: A component for selecting months.
  • AceEditorComponent: A component that integrates the Ace code editor into your application.

Directives

Directives included in the library (exported in the main module called MgmtPtlSharedModule):

  • PermissionsDirective: Restricts access to DOM elements based on user permissions.
  • StopPropagationOnClickDirective: Prevents event propagation on click.
  • AutofocusDirective: Automatically focuses on an element when it is rendered.
  • DefaultImageDirective: Replaces a broken image with a default image.
  • NeutralPersonAvatarDirective: Displays a neutral avatar if no image is provided.
  • GoBackButtonDirective: Go back to the last page visited.

Pipes

The library includes several custom pipes for use in templates (exported in the main module called MgmtPtlSharedModule):

  • MomentPipe: Formats dates using the Moment.js library.
  • ReplaceGlobalPipe: Replaces occurrences of a string globally.

Services

The library exports the following service (NOT exported in the main module):

  • MgmtPtlUtilsService: It includes a variety of helper functions for form management, string manipulation, date handling, and list operations.

Usage

To start using the main shared module, import it into your Angular application's module:

import { MgmtPtlSharedModule } from '@maspav/mgmt-ptl-shared';

@NgModule({
  imports: [
    MgmtPtlSharedModule,
  ],
})

export class AppModule {}

Examples (Pipes)

1. MomentPipe The MomentPipe is a custom Angular pipe that formats dates using the Moment.js library. It can handle various date formats and types, including Date, moment.Moment, string, and NgbDateStruct.

You can use the pipe in your templates to format dates:

<!-- Formats a date in the default format 'DD MMM, YYYY' -->
<p>{{ '2024-09-03' | momentPipe }}</p> <!-- Outputs: 03 Sep, 2024 -->

<!-- Formats a date in a custom format -->
<p>{{ '2024-09-03' | momentPipe:'YYYY/MM/DD' }}</p> <!-- Outputs: 2024/09/03 -->

<!-- Formats a time -->
<p>{{ '2024-09-03T10:15:30' | momentPipe:'HH:mm':'time' }}</p> <!-- Outputs: 10:15 -->

Methods in the MomentPipe and how they work

  • transform(value: Date | moment.Moment | string | NgbDateStruct, format: string = '', type?: 'time'): any

    • Transforms the input date or time based on the provided format and type.
    • Parameters:
      • value: The date or time to format.
      • format: The format string (optional). Defaults to 'DD MMM, YYYY'.
      • type: Specifies if the input is a time. Use 'time' for time formatting (optional).
    • Returns: The formatted date or time as a string.
  • isValidDate(value: Date | string | moment.Moment)

    • Checks if the input value is a valid date according to the format 'YYYY-MM-DD'.
    • Parameters:
      • value: The date to validate.
    • Returns: true if the date is valid, otherwise false.
  • getFormat(format: string)

    • Returns the date format string.
    • Parameters:
      • format: The format string (optional).
    • Returns: The format string provided or the default format 'DD MMM, YYYY'.

2. ReplaceGlobalPipe The ReplaceGlobalPipe is an Angular pipe that performs a global search and replace operation on a string. It uses regular expressions to replace all occurrences of a specified substring with a replacement string.

You can use the pipe in your templates to replace substrings:

<!-- Replaces all occurrences of 'world' with 'Angular' -->
<p>{{ 'Hello world!' | replace_global:'world':'Angular' }}</p> <!-- Outputs: Hello Angular! -->

Method in the ReplaceGlobalPipe and how it works

  • transform(value: string, ...args: string[]): string
    • Transforms the input string by replacing all occurrences of the first argument with the second argument.
    • Parameters:
      • value: The string on which to perform the replacement.
      • args: The first argument is the substring or pattern to search for (as a regular expression). The second argument is the replacement string.
    • Returns: The modified string with all occurrences of the pattern replaced.

Examples (Service)

1. MgmtPtlUtilsService The MgmtPtlUtilsService is a utility service provided by the @maspav/mgmt-ptl-shared library. It includes a variety of helper functions for form management, string manipulation, date handling, and list operations.

Import it into your Angular module:

import { MgmtPtlUtilsService } from '@maspav/mgmt-ptl-shared';

@NgModule({
  providers: [MgmtPtlUtilsService],
})
export class YourModule { }

Usage Here’s a basic example of how to use the service:

import { MgmtPtlUtilsService } from '@maspav/mgmt-ptl-shared';

@Component({
  selector: 'app-demo',
  template: '<div></div>',
})
export class DemoComponent {

  constructor(private utilsService: MgmtPtlUtilsService) {}

  ngOnInit() {
    // Capitalize example
    const capitalized = this.utilsService.capitalize('hello world');
    console.log(capitalized);  // Output: 'Hello World'

    // Convert date example
    const dateStruct = this.utilsService.convertDateToDateStruct('2024-09-04');
    console.log(dateStruct);  // Output: { year: 2024, month: 9, day: 4 }

    // Mark form example
    const form = new UntypedFormGroup({});
    this.utilsService.markForm(form);
  }
}

Key Functions in the Service 1. Object Utilities

  • getKeysOfObject(object: Object): string[]

    • Retrieves the keys of an object.
  • isEmpty(item: any): boolean

    • Checks whether an object, array, or string is empty.

2. String Manipulation

  • capitalize(value: string): string

    • Capitalizes the first letter of each word in a string.
  • camelCaseToWord(value: string): string

    • Converts a camelCase string to a readable string, separating words by spaces and capitalizing the first letter.
  • ucwords(value: string): string

    • Converts the first letter of each word in a string to uppercase.

3. Date Utilities

  • convertDateStructToString(date: NgbDateStruct, separator: string = '-'): string

    • Converts a NgbDateStruct (Angular Bootstrap date format) into a string.
  • formatDateDiff(date: string, type: DiffDateTypes = 'day', customDateFormat?: string): string

    • Formats the difference between the current date and a given date. Supports custom date formats.
  • convertDateToDateStruct(date?: string | moment.Moment): NgbDateStruct

    • Converts a string or moment.Moment object into an NgbDateStruct format.

4. List Utilities

  • toggleItemInList(item: any, list: any[]): void

    • Adds or removes an item from a list based on its presence.
  • isItemInList(item: any, list: any[]): any

    • Checks if an item exists in a list.
  • updateItemInList(item: any, key: string, list: any[]): any[]

    • Updates an item in a list based on a matching key.

5. Form Utilities

  • markForm(form: UntypedFormGroup | UntypedFormArray): void
    • Marks all controls in a form group or form array as touched and dirty, forcing validation.

Examples (Directives)

1. PermissionsDirective The PermissionsDirective is an Angular directive that conditionally displays a template based on the user's permissions. It checks the user's role-based and direct permissions stored in the browser and toggles the visibility of the associated template accordingly.

You can use the directive in your templates to conditionally render content based on user permissions:

<!-- This content will only be displayed if the user has the 'VIEW_DASHBOARD' permission -->
<div *permissions="['VIEW_DASHBOARD']">
  <p>This content is only visible to users with the 'VIEW_DASHBOARD' permission.</p>
</div>

<!-- This content will only be displayed if the user has both 'EDIT_USER' and 'DELETE_USER' permissions -->
<div *permissions="['EDIT_USER', 'DELETE_USER']">
  <button>Edit User</button>
  <button>Delete User</button>
</div>

Methods and Input in the PermissionsDirective and how it works

  • Input

    • permissions (string[]) : An array of permission names required to display the template. The directive will check if the current user has all the specified permissions.
  • Methods

    • permissionNames
      • Retrieves the list of all permissions available to the user, including both role-based and direct permissions.
      • Returns: An array of permission names (of type string).
    • toggleTemplate(hasPermissions: boolean)
      • Toggles the display of the template based on whether the user has the required permissions.
      • Parameters:
        • hasPermissions: A boolean indicating whether the user has all the required permissions.
      • If true, the template is displayed. If false, the template is removed from the view.

Dependencies

  • BrowserStorageService : A service that provides access to stored data in the browser, such as the current user's role and permissions.

2. StopPropagationOnClickDirective The StopPropagationOnClickDirective is an Angular directive that stops the propagation of click events. This can be useful when you want to prevent a click event from bubbling up to parent elements.

You can use the directive in your templates to stop click event propagation:

<!-- In this example, clicking the button will not trigger any click handlers attached to parent elements -->
<div (click)="parentClickHandler()">
  <button stopPropagationOnClick (click)="buttonClickHandler()">Click me</button>
</div>
  • Without the directive: Clicking the button will trigger both buttonClickHandler() and parentClickHandler().
  • With the directive: Clicking the button will only trigger buttonClickHandler(), as the event propagation is stopped.

Methods

  • onClick(event: any): void
    • The directive listens to click events on the host element and calls stopPropagation() on the event, preventing it from bubbling up to parent elements.
    • Parameters:
      • event: The click event.
    • Returns: void.

Host Listener

  • @HostListener('click', ['$event'])
    • The directive uses the @HostListener decorator to listen for click events on the host element.

3. NeutralPersonAvatarDirective The NeutralPersonAvatarDirective is an Angular directive that provides a default image for an <img> element if the specified image fails to load. This is useful for handling cases where user avatars or other images may be missing or unavailable.

You can apply the directive to an <img> element in your templates:

<!-- If the user's avatar fails to load, a neutral placeholder image will be displayed instead -->
<img [src]="user.avatarUrl" defaultNeutralPerson />

Methods and Input in the NeutralPersonAvatarDirective and how it works

  • Input

    • src (string): The source URL of the image. This is the image that will be displayed if it loads successfully.
  • Methods

    • onError()
      • This method is called when the image fails to load. It sets the src attribute to the default neutral person image.
      • Returns: void.

Host Bindings and Listeners

  • Host Configuration:
    • '(error)': Triggers the onError() method when an error occurs while loading the image.
    • '[src]': Binds the src attribute of the element to the src property of the directive.

4. DefaultImageDirective The DefaultImageDirective is an Angular directive that provides a fallback image for an <img> element if the specified image fails to load. You can specify a custom default image or use a general placeholder.

You can apply the directive to an <img> element in your templates:

<!-- If the specified image fails to load, the directive will use the custom default image -->
<img [src]="'/assets/images/user-profile.png'" [default]="'/assets/images/default-avatar.png'" default />

<!-- If the custom default image is not provided, it will fall back to a general placeholder -->
<img [src]="'/assets/images/nonexistent-image.png'" default />

In the first example, if '/assets/images/user-profile.png' fails to load, the image will be replaced with '/assets/images/default-avatar.png'. In the second example, if '/assets/images/nonexistent-image.png' fails to load, the image will be replaced with the general placeholder at '/assets/images/placeholders/image-icon.jpg'.

Methods and Inputs in the DefaultImageDirective and how it works

  • Inputs

    • src (string): The source URL of the image. This is the image that will be displayed if it loads successfully.
    • default (string): The URL of the default image to be used if the original image fails to load.
  • Methods

    • onError()
      • This method is called when the image fails to load. It sets the src attribute to the custom default image if provided, or falls back to a general placeholder.
      • Returns: void.

Host Bindings and Listeners

  • Host Configuration:
    • '(error)': Triggers the onError() method when an error occurs while loading the image.
    • '[src]': Binds the src attribute of the <img> element to the src property of the directive.

5. AutofocusDirective The AutofocusDirective is an Angular directive that automatically sets focus on an element when it is rendered. This is particularly useful for forms or modals where you want a specific input field to be focused as soon as it appears.

You can apply the directive to any focusable element in your templates:

<!-- The input field will automatically receive focus when the component is loaded -->
<input type="text" placeholder="Enter your name" autofocus />

<!-- This directive can be applied to other elements like textareas or select inputs -->
<textarea autofocus></textarea>

In these examples, the AutofocusDirective will automatically focus on the input or textarea when the component is rendered.

How the AutofocusDirective works

  • ngAfterViewInit()
    • The directive uses the ngAfterViewInit() lifecycle hook to ensure that the element is focused after it has been fully initialized.
  • Constructor
    • constructor(private elementRef: ElementRef)
      • The directive injects ElementRef to gain direct access to the DOM element on which the directive is applied. It then calls the focus() method on this element to set focus.
  • Method Implementation

    • this.elementRef.nativeElement.focus()

    Examples (Components)

    1. SpinnerComponent The SpinnerComponent is a reusable loading spinner that can be customized in terms of its appearance and positioning. It provides visual feedback during loading processes, indicating that an action is in progress.

You can use the component in your templates:

<!-- Default usage with the spinner centered and styled as 'text-primary mt-1' -->
<mgmt-ptl-spinner></mgmt-ptl-spinner>

<!-- Custom usage with the spinner positioned on the left and styled as 'text-danger mt-2' -->
<mgmt-ptl-spinner [customClass]="'text-danger mt-2'" [position]="'left'"></mgmt-ptl-spinner>

<!-- You can also include additional content inside the spinner component -->
<mgmt-ptl-spinner [position]="'right'">
  Loading your data, please wait...
</mgmt-ptl-spinner>

Inputs

  • customClass (string) (Optional): CSS classes to customize the appearance of the spinner. The default value is 'text-primary mt-1'.
  • position ('left' | 'center' | 'right') (Optional): Specifies the position of the spinner within its container. The default value is 'center'.

2. PaginationComponent The PaginationComponent is a reusable Angular component designed to handle pagination in your application. It supports various types of pagination data and emits events when the page is changed, making it easy to manage paginated data.

You can use the component in your templates:

<!-- Pagination component usage -->
<mgmt-ptl-pagination [paginate]="paginatorData" (pageChange)="onPageChange($event)"></mgmt-ptl-pagination>

In your component class

//Example values 
paginatorData: Paginator = {
  collectionSize: 100,
  page: 1,
  total: 100,
  from: 1,
  to: 10,
  perPage: 10,
  disabled: false,
  pages: 10
};

onPageChange(pageNumber: number) {
  console.log('Page changed to:', pageNumber);
  // Handle the page change logic here
}

Inputs

  • paginate (Paginator): The pagination data object containing various properties such as:
    • collectionSize (number | any): The total number of items in the collection.
    • page (number | any): The current page number.
    • total (number): The total number of items being paginated.
    • from (number): The starting index of the items on the current page.
    • to (number): The ending index of the items on the current page.
    • perPage (number): The number of items per page.
    • disabled (boolean): If true, disables the pagination controls.
    • pages (number): The total number of pages.

Outputs

  • pageChange (EventEmitter<any>): Emits the current page number whenever the user changes the page. This allows the parent component to handle the new page number and fetch corresponding data.

Template Structure

  • The component uses Bootstrap’s ngb-pagination directive for the pagination controls.
  • The current page's item range (from-to) and the total number of items are displayed on the left.
  • The pagination controls are displayed on the right, with custom "Previous" and "Next" buttons.

Example Scenarios a. Basic Pagination:

  • Show a list of items with pagination controls at the bottom, allowing users to navigate between different pages of data.b. Server-Side Pagination:
  • Handle large datasets by fetching only the items for the current page from the server, updating the Paginator object accordingly.

Customization

  • Customize the appearance of the pagination controls using Bootstrap classes.
  • Adjust the paginate input to match the data format returned by your API or data source.

3. PageUnderConstructionComponent The PageUnderConstructionComponent is a simple Angular component that displays a "page under construction" message. It is designed to be used as a placeholder on pages that are not yet implemented or are being developed.

You can use the component in your templates:

<!-- Default usage -->
<mgmt-ptl-page-under-construction></mgmt-ptl-page-under-construction>

<!-- Customized usage -->
<mgmt-ptl-page-under-construction
  [title]="'Feature Coming Soon!'"
  [subtitle]="'We're working hard to bring you this feature. Stay tuned!'">
</mgmt-ptl-page-under-construction>

Inputs

  • title (string): The main title to be displayed on the page. Default is "This page is under construction!".
  • subtitle (string): An optional subtitle to provide additional context or information about the page status.

Template Structure

  • The component uses Bootstrap classes to center the content and style the text.
  • The default illustration is an SVG image (assets/images/illustration/undrawunder_construction-46-pa.svg) that conveys the "under construction" message visually.
  • The main title (title) is displayed as a large heading, and the optional subtitle (subtitle) is shown beneath it.

Example Scenarios a. Placeholder for Incomplete Features:

  • Use this component to display a friendly message on pages that are still under development, providing users with clear communication about ongoing work.

    b. Temporary Pages:

  • Employ this component on pages that are not yet ready to be launched but are part of the application's navigation.

4. BulletComponent The BulletComponent is a simple Angular component that displays a bullet symbol (•) with customizable styling. It can be used in lists or other components where a bullet point is needed to indicate items or sections.

You can use the component in your templates:

<!-- Default usage -->
<mgmt-ptl-bullet></mgmt-ptl-bullet>

<!-- Customized usage with a custom CSS class -->
<mgmt-ptl-bullet [class]="'text-danger font-weight-bold'"></mgmt-ptl-bullet>

Input

  • class (string): The CSS class or classes to apply to the bullet symbol. Default is "mx-1 font-14".

Example Scenarios a. List Items:

  • Use this component to create a styled list of items, with the bullet component indicating each item.

    b. Section Separators:

  • Employ this component to visually separate different sections or elements on a page with a bullet symbol.

5. NoRecordsComponent The NoRecordsComponent is a simple component that displays a message and an image when there are no records to show. It is typically used in scenarios where you want to inform the user that there is no data available.

You can use the component in your templates:

<mgmt-ptl-no-records [centered]="true" message="No records found"></mgmt-ptl-no-records>

Inputs

  • centered: boolean

    • Default: true
    • Description: Determines whether the content (image and message) is centered within its container.
  • message: string

    • Description: The message displayed when there are no records to show.

6. AceEditorComponent The AceEditorComponent is an Angular component that integrates the Ace code editor into your application. It allows you to customize the editor's theme, mode, and options while emitting changes made to the editor's content.

Features

  • Configurable editor height, theme, and mode.
  • Emits editor content changes via an EventEmitter.
  • Provides a method to reset the editor to its initial content.

Usage Import the Component into your Angular module:

import { AceEditorComponent } from '@maspav/mgmt-ptl-shared';
@NgModule({
  declarations: [
     AceEditorComponent
  ],
})
export class YourModule {}

You can then use the component in your templates:

<mgmt-ptl-ace-editor 
  [configData]="myConfigData" 
  [theme]="'ace/theme/monokai'" 
  [mode]="'ace/mode/javascript'" 
  [height]="500" 
  [options]="editorOptions" 
  (onChange)="handleEditorChange($event)">
</mgmt-ptl-ace-editor>

In your component class

 export class ExampleComponent {
  myConfigData = { key: 'value' };
  editorOptions = { fontSize: '14px' };

  handleEditorChange(newValue: string) {
    console.log('Editor content changed:', newValue);
  }

Inputs

  • configData: Initial data to populate the editor (optional).
  • theme: The theme for the editor (optional). Defaults to 'ace/theme/eclipse'.
  • mode: The mode for the editor (optional). Defaults to "ace/mode/json".
  • height: The height of the editor in pixels (optional).
  • options: Additional options to configure the Ace editor (optional).

Outputs

  • onChange: Emits the current content of the editor whenever a change is detected.

7. ConfirmationModalComponent The ConfirmationModalComponent is a customizable confirmation modal component for Angular applications. It provides a modal dialog box with configurable title, message, and buttons for confirming or canceling an action.

Features

  • Customizable title, message, button text, and modal type.
  • Emits events when the modal is confirmed or closed.
  • Supports dynamic content insertion in the modal body and footer.

You can use the component in your templates:

<mgmt-ptl-confirmation-modal 
  [modal]="activeModal" 
  [modalTitle]="'Delete Confirmation'" 
  [type]="'danger'" 
  [loading]="isDeleting" 
  [confirmBtnText]="'Delete'" 
  [cancelBtnText]="'Cancel'"
  (confirmed)="onConfirmDelete()"
  (closed)="onCloseModal(modal)">
  
  <div body>
    Are you sure you want to delete this item?
  </div>
  
  <div footer>
    <button type="button" class="btn btn-secondary" (click)="onCloseModal(modal)">Cancel</button>
    <button type="button" class="btn btn-danger" [disabled]="isDeleting" (click)="onConfirmDelete()">Delete</button>
  </div>
</mgmt-ptl-confirmation-modal>

In your component class

import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

export class ExampleComponent {
  isDeleting = false;
  activeModal: NgbActiveModal;

  constructor() {}

  onConfirmDelete() {
    this.isDeleting = true;
   //implement delete logic here.
  }

  onCloseModal(template?: any) {
    // closing modal logic
    template.close();
  }
}

Inputs

  • modal: The active modal instance (NgbActiveModal).
  • modalTitle: The title of the modal (optional, default: 'Confirm').
  • message: The message displayed in the modal body (optional).
  • type: The type of the modal, which controls the styling of the buttons (e.g., 'primary', 'danger').
  • loading: Indicates if a loading spinner should be displayed in the confirm button (optional, default: false).
  • confirmBtnText: The text for the confirm button (optional, default: 'Yes').
  • cancelBtnText: The text for the cancel button (optional, default: 'Cancel').

Outputs

  • confirmed: Emits when the confirm button is clicked.
  • closed: Emits when the modal is closed, either by clicking the cancel button or programmatically.

8. ContentHeaderComponent The ContentHeaderComponent is a reusable component designed to display a page's title and breadcrumb navigation in Angular applications. It dynamically updates based on the current route's data or can be manually configured via an input property.

Features

  • Automatically sets the page title using Angular's Title service.
  • Displays a breadcrumb navigation trail based on the current route or provided input.
  • Customizable via input properties or automatic routing data.

You can use the component in your templates (Manual Configuration):

<mgmt-ptl-content-header [contentHeader]="headerConfig"></mgmt-ptl-content-header>

In your component class (Manual Configuration)

export class ExampleComponent implements OnInit {
   headerConfig = {
    title: 'Page Title',
    breadcrumbs: [
      { title: 'Home', url: '/' },
      { title: 'Section', url: '/section' },
      { title: 'Page', url: '/section/page' }
    ]
  };

}

Alternatively, in your route definitions, include title and breadcrumbs in the data property (Route Configuration)

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    data: {
      title: 'Home',
      breadcrumbs: [{ title: 'Home', url: '/' }]
    }
  },
  {
    path: 'section',
    component: SectionComponent,
    data: {
      title: 'Section',
      breadcrumbs: [
        { title: 'Home', url: '/' },
        { title: 'Section', url: '/section' }
      ]
    }
  },
  {
    path: 'section/page',
    component: PageComponent,
    data: {
      title: 'Page',
      breadcrumbs: [
        { title: 'Home', url: '/' },
        { title: 'Section', url: '/section' },
        { title: 'Page' }
      ]
    }
  }
];

You can use the component in your templates (Route Configuration):

<mgmt-ptl-content-header></mgmt-ptl-content-header>

The ContentHeaderComponent will automatically pick up these values and display the title and breadcrumbs accordingly.

Inputs

  • contentHeader: The configuration object for the content header, including the page title and breadcrumbs. Code below.
export interface ContentHeader {
  title: string;
  breadcrumbs?: Breadcrumb[];
}

interface Breadcrumb {
  title: string;
  url?: string;
  params?: any;
}

9. ContentWrapperComponent The ContentWrapperComponent is a simple utility component designed to wrap content within a configurable container. It provides flexibility in adjusting the container's width based on the fullWidth (boolean) input property. The ContentWrapperComponent wraps its content in either a full-width container or a standard-width container based on the fullWidth (boolean) property.

Using the Component in Your Templates By default, the content will be wrapped in a standard-width container.

<mgmt-ptl-content-wrapper>
  <!-- Your content here -->
</mgmt-ptl-content-wrapper>

To make the container span the full width of the viewport, set the fullWidth input property to true.

<mgmt-ptl-content-wrapper [fullWidth]="true">
  <!-- Your full-width content here -->
</mgmt-ptl-content-wrapper>

10. FormErrorsComponent The FormErrorsComponent is a reusable Angular component designed to display validation error messages for form controls. It dynamically handles different types of errors and supports customization of error messages.

Basic Usage

<form [formGroup]="yourForm">
  <div>
    <label for="email">Email</label>
    <input id="email" formControlName="email" />
    <mgmt-ptl-form-errors [control]="yourForm.get('email')"></mgmt-ptl-form-errors>
  </div>
</form>

In this example above, the component will automatically display the appropriate error message when the email field is invalid and touched.

Custom Validation Messages You can pass custom validation messages using the componentValidation input.

<mgmt-ptl-form-errors
  [control]="yourForm.get('password')"
  [componentValidation]="{
    required: { message: 'Password is required!' },
    minlength: { message: 'Password must be at least 8 characters long.' }
  }"
></mgmt-ptl-form-errors>

This allows you to override the default messages with your custom messages.

Default Error Messages

  • The FormErrorsComponent comes with a set of default error messages for common validation errors. These include:

    • required: "This field is required"
    • email: "The email entered is invalid"
    • passwordMismatch: "Your passwords do not match"
    • minlength: "You must enter at least {length} characters"
    • maxlength: "You must not enter more than {length} characters"
    • pattern: "Your entry must match the required pattern"

    If no custom validation messages are provided, these defaults will be used.

11. ModalWrapperComponent The ModalWrapperComponent is a customizable modal component designed to work within Angular applications. It provides a flexible wrapper for modals, allowing developers to define modal content, actions, and styles with ease. The component integrates seamlessly with NgbActiveModal from @ng-bootstrap/ng-bootstrap.

Basic Usage

<mgmt-ptl-modal-wrapper
  [modal]="modalInstance"
  [modalTitle]="'My Modal Title'"
  [type]="'primary'"
  [showFooter]="true"
  (confirm)="onConfirm()"
  (cancel)="onCancel()"
  (closed)="onModalClose(modal)"
>
  <ng-container title>
    <!-- Optional: Custom title content -->
  </ng-container>
  
  <ng-container body>
    <!-- Modal body content here -->
    <p>This is the content of the modal.</p>
  </ng-container>
  
  <ng-container footer>
    <!-- Optional: Custom footer content -->
  </ng-container>
</mgmt-ptl-modal-wrapper>

Handling Modal Events You can listen to the emitted events from the ModalWrapperComponent to handle confirm, cancel, and close actions.

import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

export class YourComponent {
  modalInstance: NgbActiveModal;

  onConfirm() {
    // Handle confirm action
  }

  onCancel() {
    // Handle cancel action
  }

  onModalClose(template?:any) {
    // closing modal logic
    template.close();
  }
}

Inputs:

  • modal (NgbActiveModal): The active modal instance to control modal actions like close and dismiss.
  • showHeader (boolean): Determines whether the modal header is displayed. Default is true.
  • modalTitle (string): The title text for the modal.
  • showFooter (boolean): Determines whether the modal footer is displayed. Default is true.
  • type (ModalTypes): The type of modal, affecting the header's color and title text color. Can be one of 'primary' | 'success' | 'danger' | 'info'.
  • showConfirmBtn (boolean): Determines whether the confirm button is displayed in the footer. Default is true.
  • confirmBtnText (string): The text displayed on the confirm button. Default is 'Save Changes'.
  • confirmBtnClass (string): Additional CSS classes for the confirm button.
  • showCancelBtn (boolean): Determines whether the cancel button is displayed in the footer. Default is true.
  • cancelBtnText (string): The text displayed on the cancel button. Default is 'Cancel'.
  • cancelBtnClass (string): Additional CSS classes for the cancel button.
  • showCloseIcon (boolean): Determines whether the close icon (X) is displayed in the header. Default is true.

Outputs:

  • confirm (EventEmitter): Emitted when the confirm button is clicked.
  • cancel (EventEmitter): Emitted when the cancel button is clicked.
  • closed (EventEmitter): Emitted when the modal is closed.

Customization Options The ModalWrapperComponent allows for extensive customization:

  • Modal Header:

    • You can set a custom title using modalTitle or provide custom header content using the title selector.
    • The close icon can be toggled on or off with the showCloseIcon input.
  • Modal Footer:

    • The footer can include custom buttons or elements using the footer selector.
    • Default confirm and cancel buttons are provided but can be customized or removed as needed.
  • Modal Types:

    • The modal header and title text color can be customized by setting the type input to 'primary', 'success', 'danger', or 'info'.

12. StaffListComponent The StaffListComponent is an Angular component designed to display a list of staff members, including search, pagination, and selection functionality. It integrates with a backend service (through Staff Service) to fetch staff data and provides a customizable UI for managing staff members.

Features

  • Search Functionality: Allows users to search staff members by name or title.
  • Pagination: Supports pagination for navigating through large lists of staff members.
  • Selection: Users can select and manage a list of staff members with the ability to limit the number of selectable members.
  • Customizable Display: The component can be customized to show staff from a specific department and hide or disable certain staff members.

Usage Here is an example of how to use it in your template.

<mgmt-ptl-staff-list
  [department]="'Engineering'"
  [selectedStaffsEmails]="['john.doe@example.com']"
  [disabledStaffsEmails]="['jane.smith@example.com']"
  [hiddenStaffsEmails]="['hidden.staff@example.com']"
  [maxSelect]="5"
  (staffSelected)="onStaffSelected($event)"
  (staffRemoved)="onStaffRemoved($event)">
</mgmt-ptl-staff-list>

Inputs

  • department (string): The department from which to fetch staff members.
  • selectedStaffsEmails (string[]): A list of emails representing the staff members who are initially selected.
  • disabledStaffsEmails (string[]): A list of emails representing the staff members who should be disabled (unselectable).
  • hiddenStaffsEmails (string[]): A list of emails representing the staff members who should be hidden from the list.
  • maxSelect (number): The maximum number of staff members that can be selected.

Outputs

  • staffSelected (EventEmitter<any>): Emits the selected staff member when a user selects one.
  • staffRemoved (EventEmitter<any>): Emits the removed staff member when a user removes one from the selected list.

13. MonthPickerComponent The MonthPickerComponent is an Angular component that allows users to select a specific month within a year, with options to navigate between years. This component can be used for custom date picking where the user needs to select a month in a range of years.

Features

  • Year Navigation: Users can move between years using "Previous" and "Next" buttons.
  • Month Selection: Users can select a specific month from a list.
  • Period Application: Once the user selects a month, they can apply the selection, emitting the selected date.
  • Min/Max Constraints: Define a minimum and maximum period to limit the range of selectable months and years.

Usage Here’s how to integrate MonthPickerComponent into your template:

<mgmt-ptl-month-picker
  [selectedPeriod]="selectedPeriod"
  [min]="minPeriod"
  [max]="maxPeriod"
  (dateApplied)="onDateApplied($event)">
</mgmt-ptl-month-picker>

In your component class

import { Period } from from '@maspav/mgmt-ptl-shared';

export class YourComponent {
  selectedPeriod = { year: 2023, month: 7 };
  minPeriod = { year: 2020, month: 1 };
  maxPeriod = { year: 2025, month: 12 };

  onDateApplied(period: Period) {
    console.log('Selected Period:', period);
  }
}

Inputs

  • selectedPeriod: Period:

    • The initial period that the picker will display. This is an object with year and month properties.
    • Example: { year: 2024, month: 5 }
  • min: Period:

    • The minimum period (year and month) that can be selected. This restricts the month and year navigation.
    • Example: { year: 2020, month: 1 }
  • max: Period:

    • The maximum period (year and month) that can be selected.
    • Example: { year: 2025, month: 12 }

Outputs

  • dateApplied: EventEmitter<Period>:
    • Emits the selected period (year and month) when the "Apply" button is clicked.

14. InstantExportButtonComponent The InstantExportButtonComponent provides a customizable button for downloading data, which triggers an export process through the ExportService. It is part of the @maspav/mgmt-ptl-shared library and leverages the MgmtPtlSharedModule.

Usage You can use the InstantExportButtonComponent in your templates by adding the download-button selector and configuring the downloadConfig input.

<download-button 
  [downloadConfig]="downloadConfig" 
  [customClass]="'custom-class'">
</download-button>

Example Configuration for downloadConfig in your components typescript

downloadConfig = {
  totalRecordLength: 500,
  endpoint: '/api/exports/download',
  model: 'Transaction',
  tableHeaders: ['ID', 'Amount', 'Date'],
  listData: [{'ITC101','5000','01-08-2024'},{'ITC101','5000','01-08-2024'},{'ITC101','5000','01-08-2024'}], // Array of transaction data to be exported
  fileName: 'transactions_export'
};

Export Configuration The downloadConfig object should include:

  • totalRecordLength: Total number of records to be exported.
  • endpoint: API endpoint from which the export request will be made.
  • model: Data model being exported.
  • tableHeaders: Headers of the table representing the data to be exported.
  • listData: Array of data to be exported.
  • fileName: Name of the exported file.

Styling The component allows for custom styling using the customClass input. You can define your custom class in your stylesheet and apply it to the button.

.custom-class {
  background-color: #007bff;
  color: white;
  padding: 10px;
}

15. ExportComponent The ExportComponent is a reusable Angular component for exporting data based on specific date filters (e.g., today, yesterday, a specific date, a date range, or monthly). It provides a modal interface for configuring export settings and uses forms to specify date filters. The component is highly configurable and allows for dynamic column selection and additional parameters for the export.

Usage In your HTML template, you can invoke the ExportComponent by including its selector. You will need to provide necessary @Input() values for configuring the export, including title, export type, data, and configuration.

<export
  [modal]="modal"
  [modalTitle]="'Export Data'"
  [type]="exportType"
  [modalData]="dataToExport"
  [config]="exportConfig"
  (confirmed)="onExportConfirmed($event)"
  (closed)="onExportClosed()">
</export>

Example configuration in your Component class

exportConfig = {
  dataSet: ['transaction_id', 'amount', 'date'],
  recipients: ['user@example.com'],
  url: '/api/transactions/export',
  filter: { transaction_date: '2024-09-04' }
};

onExportConfirmed($event){
  // handle logic
}

onExportClosed(){
  // close modal logic
}

Inputs

  • modal: An instance of NgbActiveModal to control modal behavior.
  • modalTitle: Title of the export modal (default: 'Export').
  • type: Type of export (use any type you wish to define).
  • modalData: Additional data for the export (optional).
  • config: Configuration object for the export. It should include:
  • dataSet: Columns or fields to be exported.
  • recipients: Array of recipient email addresses.
  • url: The API endpoint to post the export request.
  • filter: (Optional) A filter object to apply additional filter parameters.

Outputs

  • confirmed: Emitted when the export is confirmed, containing the export payload.
  • closed: Emitted when the modal is closed without confirming the export.

Date Filter Tabs The component includes date filter tabs to choose between i.e., Yesterday, Today, A specific date, A monthly period, A custom date range.

Validators and Error Handling The component uses Angular forms with validation logic to ensure all required fields are filled. If an export request fails, a notification will be shown using ngx-toastr.

Dependencies

  • @ng-bootstrap/ng-bootstrap: For modal and date picker functionality.
  • ngx-toastr: For user notifications.
  • moment: For handling date calculations.

16. FiltersComponent The FiltersComponent is an Angular component provided by the MgmtPtlSharedModule. It offers a configurable UI for filtering data, applying filters, and clearing them. The component is highly customizable via the FilterConfig input and works in conjunction with services like FilterService and MgmtPtlUtilsService to handle form creation, filtering logic, and navigation with applied filters.

Features

  • Dynamic form generation based on the filter configuration.
  • Supports various input types: text, options (single/multiple), lists, and dates.
  • Emits events for applied and cleared filters.
  • Provides functionality to disable filter submission until valid input is detected.

Using the Component Once the module is imported, you can use the FiltersComponent in your template by adding the selector mgmt-ptl-filters.

<mgmt-ptl-filters
  [config]="filterConfig"
  (applied)="onFiltersApplied($event)"
  (cleared)="onFiltersCleared()"
></mgmt-ptl-filters>

Here’s an example of how to configure the component in your component class:

import { FilterConfig } from '@maspav/mgmt-ptl-shared';

filterConfig: FilterConfig = {
  fields: [
    { key: 'name', label: 'Name', type: 'text', required: true },
    { key: 'category', label: 'Category', type: 'options', options: { data: ['Option 1', 'Option 2'], selectMultiple: false } },
    { key: 'date', label: 'Created Date', type: 'date' }
  ],
  endpoint: '/api/data/filters',
  selectedFields: []
};

onFiltersApplied(response: FiltersAppliedResponse) {
  // handle applied filters logic
  console.log('Filters applied with params:', response.params);
  console.log('Server response:', response.response);
}

onFiltersCleared() {
  // handle clearing logic
  console.log('Filters cleared');
}

Inputs

  • config (FilterConfig): Configuration object that defines the form fields, their types, and the API endpoint.

The code below shows the definition of the FilterConfig interface.

type FormFieldTypes = 'text' | 'options' | 'date'| 'daterange' | 'typeahead';

interface FormFieldDateRange {
  startKey: string;
  endKey: string;
}
interface FormFieldOptions {
  data: any[] | Observable<any[]>;
  url?: string;
  loading?: boolean;
  label?: string;
  value?: string;
  selectMultiple?: boolean;
  elapsedTime?:string | number
  minTermLength?: number;
  placeholder?: string;
}
export interface FormField {
  type: FormFieldTypes;
  key: string;
  label: string;
  required?: boolean | 'false' | any;
  options?: FormFieldOptions | any;
  dateRange?: FormFieldDateRange | any;
  value?:string | number | boolean | Object;
}
export interface FilterConfig {
  fields: FormField[];
  endpoint: string;
  selectedFields: FormField[];
  appliedParams?: any;
}
export interface FiltersAppliedResponse {
  params: any;
  response: any;
}

Outputs

  • applied: Emits a FiltersAppliedResponse when filters are successfully applied. The event contains the query parameters and the server response.
  • cleared: Emits when the filters are cleared.

17. FilterButtonComponent The FilterButtonComponent is an Angular component that ships with the MgmtPtlSharedModule. It provides a dropdown button that toggles filters on and off for use in filtering datasets or views. The component allows users to select or deselect filters dynamically and emits events to handle these changes. The filters available in the dropdown are based on a provided configuration (FilterConfig), and the component interacts with the FilterService to manage selected filters.

Dependencies

  • MgmtPtlUtilsService: A utility service used to manage selected items in the filter list.
  • FilterService: A service used to handle filter selection and emits events related to filter toggling.

Example Usage In your component's template:

<mgmt-ptl-toggle-filters-btn [customClass]="'btn-sm'" [config]="filterConfig"></mgmt-ptl-toggle-filters-btn>

In your component's TypeScript:

import { FilterConfig } from '@maspav/mgmt-ptl-shared';

export class MyComponent {
  filterConfig: FilterConfig = {
    fields: [
      { key: 'name', label: 'Name', type: 'text' },
      { key: 'date', label: 'Date', type: 'date' }
    ],
    selectedFields: []
  };
}

Inputs

  • customClass (optional): Custom CSS classes that will be applied to the filter button.
  • config (required): FilterConfig object that defines the available fields and the currently selected fields (refer to FilterConfig interface above).

18. AdvancedFiltersComponent The AdvancedFiltersComponent is part of the @maspav/mgmt-ptl-shared library. It is a configurable component that provides advanced filtering capabilities, allowing users to apply and clear filters on a dataset. The component dynamically generates forms based on the configuration passed in via the config input, supporting various field types like options, typeahead, date, and date range filters.

Example Usage In your component's template:

<mgmt-ptl-advanced-filters
  [config]="filterConfig"
  (applied)="onFiltersApplied($event)"
  (cleared)="onFiltersCleared()"
></mgmt-ptl-advanced-filters>

In your component's TypeScript:

import { FilterConfig } from '@maspav/mgmt-ptl-shared';

const filterConfig: FilterConfig = {
  selectedFields: [
    { key: 'status', label: 'Status', type: 'options', options: { data: ['Active', 'Inactive'] } },
    { key: 'created_at', label: 'Created At', type: 'daterange', dateRange: { startKey: 'start_date', endKey: 'end_date' } },
  ],
  endpoint: '/api/data',
};

This configuration will create a filter form with a dropdown for status and a date range picker for the creation date. When the user applies filters, the component will make a request to /api/data with the selected filter values.

Inputs

  • config: FilterConfig
    • This is the main configuration object that defines the available filters, the endpoint to fetch the filtered data, and the currently selected fields (refer to FilterConfig interface above).

Outputs

  • applied: EventEmitter<FiltersAppliedResponse>

    • Emitted when the filters are applied, passing the applied parameters and the response data.
  • cleared: EventEmitter<any>

    • Emitted when the filters are cleared.
1.1.4

9 months ago

1.1.3

10 months ago

1.1.1

10 months ago

1.1.0

10 months ago

1.1.2

10 months ago

1.0.0

10 months ago

0.0.19

10 months ago

0.0.15

11 months ago

0.0.16

11 months ago

0.0.17

11 months ago

0.0.18

11 months ago

0.0.14

11 months ago

0.0.13

11 months ago

0.0.12

11 months ago

0.0.11

11 months ago

0.0.10

11 months ago

0.0.9

11 months ago

0.0.8

11 months ago

0.0.7

11 months ago

0.0.0-watch

11 months ago

0.0.6

11 months ago

0.0.5

11 months ago

0.0.4

11 months ago

0.0.3

11 months ago

0.0.2

11 months ago

0.0.1

11 months ago