npm package: @indigina/angular
Description: Shared angular components for Indigina projects.
Latest version: 1.0.67-beta

# @indigina/angular

This library contains shared angular components for Indigina projects.

---

##### Table of Contents

1. [Install](#install)

2. [Configuration](#library-configuration)

3. [Components](#components)

   - [Tree-View Component](#tree-view-component)

   - [Side-Menu Component](#side-menu-component)

   - [Form Components](#form-components)

     - [FormGroupWithErrors](#formgroupwitherrors)

     - [General-Errors Component](#general-errors-component)

     - [FieldInput Component](#fieldinput-component)

     - [NumberInput Component](#numberinput-component)

   - [Debounce Directive](#debounce-directive)

4. [Services](#services)

   - [TranslateSettingsService](#translatesettingsservice)

   - [HttpService](#httpservice)

   - [AppToastrService](#apptoastrservice)

5. [Models](#models)

   - [AppSettings](#appsettings)

   - [CustomHttpErrorResponse](#customhttperrorresponse)

   - [HttpCodes](#httpcodes)

   - [HttpMethods](#httpmethods)

   - [IdentifiedModel](identifiedmodel)

   - [IndiginaConfiguration](#indiginaconfiguration)

   - [Languages](#languages)

   - [NamedModel](#namedmodel)

6. [Provided Packages](#provided-packages)

7. [Exports Table](#exports-table)

---

# Install

## Before installing.

> The library depends for packages next versions: **@ngx-translate ">12.0.0"** and **ngx-clipboard ">12.0.0"**.
>
> If your application depends on the following package versions below the recommended ones, you should update the packages or simply delete them in **"package.json"** file, in which case the latest version of the packages will be installed.
>
> **_Make sure your_ package.json _file contains packages of the recommended version._**

To install the package you'll need enter command at terminal

    npm i @indigina/angular --save

Open your module file e.g. app.module.ts and update **imports** array:

    import { IndiginaModule } from '@indigina/angular';
    import {  ReactiveFormsModule  } from '@angular/forms';

    ...

    imports: [
        ...
        IndiginaModule,
        ReactiveFormsModule,
        ...
    ]

Also, you need to setup the routes and import **RouterModule**. [How to Setup](https://angular.io/api/router/RouterModule)

Open your global style file for application e.g. **styles.css** and add the following:

    @import @indigina/angular/assets/indigina-theme.css

> # Important notes:
>
> The **@indigina/angular** provides the TranslationModule from **@ngx-translate** package (List of [provided packages](#provided-packages)). You can use **translate** pipe without any additional includes in your app.
>
> The **@indigina/angular** also provides **_TranslateSettingsService_** for set or get current locale [See more](#translatesettingsservice).
>
> For setup **TranslationModule** see [Library Configuration](#library-configuration)

---

# Library Configuration

For configure library you must use a [**IndiginaConfiguration**](#indiginaconfiguration) interface

**IndiginaConfiguration** abstract class is provided for @indigina/angular library configuration.

### IndiginaConfiguration class overview

| Param Name  | Required | Type            | Description                                                                                                                                                                                                                                                                         |
| ----------- | -------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| langs       | no       | TranslateLoader | The Translate module config. If you provide **langs** then @indigina/angular use the factory config, fo more information see [original documentation](https://www.npmjs.com/package/@ngx-translate/core). And see an example of [Setup TranslationModule](#setup-translationmodule) |
| appSettings | no       | AppSettings     | The basic Application settings for working with server endpoint.                                                                                                                                                                                                                    |

## Setup TranslationModule

For setup **TranslationModule** you needs to push the TranslateLoader to library, for example open your module file e.g. **app.module.ts** and update next:

    ...

    const langs = {
        'en' = {
            UserName: 'User Name',
        },
        'ru' = {
            UserName: 'Имя пользователя',
        },
        getTranslations(lang: string): Observable<any> {
            if (Object.keys(this).includes(lang)) {
                return of(this[lang]);
            }

            return of(this['en']);
        }
    }

    ...

    imports: [
    ...
    IndiginaModule.forRoot({ langs })
    ...
    ]

## Setup AppSettings

To use the [HttpService](#httpservice) and the [AppToastrService](#apptoastrservice) you need to setup library with appSettings.
For setup library to use provided services, you need to push [AppSettings](#appsetiings) to library, for example open your module file e.g. **app.module.ts** and update next:

    ...

    const appSettings = {
        apiUrl: 'http://localhost:8080/',
        accountUrl: 'http://localhost:3000/signin/',
        toastrTimeOut: 3000
    }

    ...

    imports: [
    ...
    IndiginaModule.forRoot({ appSettings })
    ...
    ]

---

# Components

## Tree-View Component

Selector: **tree-view**

This component shows any type of content (XML, JSON) as a tree. The text data will be rendered inside the `<pre>` tag.
The component accepts input parameters:

- **[data: string]** - the data to view
- **[maxTextLength: number] (optional)** - the maximum text length that will be displayed, otherwise hidden and expand button is shown (default is **1200**)
- **[maxRootItems: number] (optional)** - the maximum root nodes that will be displayed, otherwise hidden and expand button is shown (default is **10**)

### Tree-View Component Usage:

    <tree-view [data]="data"></tree-view>


    <tree-view [data]="data" [maxRootItems]="15"></tree-view>

## Side-Menu Component

Selector: **side-menu**

This component displays a menu.
Used input parameter **[items]** with type **MenuItem[]**:

### MenuItem type overview

| Param name    | Required | Type       | Description                                                                                 |
| ------------- | -------- | ---------- | ------------------------------------------------------------------------------------------- |
| **text**      | yes      | string     | Text to show. It will be translated by **_translate_** pipe inside (@ngx-translate package) |
| **url**       | no       | string     | Use for external url link                                                                   |
| **link**      | no       | string     | Use for internal url route                                                                  |
| **iconClass** | no       | string     | The class of icon. For exapmle: 'fa fa-dashboard'                                           |
| **expanded**  | no       | boolean    | You can set expand flag manually. Child elements are displayed if flag is set to **_true_** |
| **items**     | no       | MenuItem[] | Collection of child menu items                                                              |

### Side-Menu Component Usage

Inside the template class

    <side-menu [items]="items">

Inside your component class

    public items: MenuItem[];

    ...

    this.items = [
        {
            text: 'Home',
            iconClass: 'fa fa-home',
            link: '/'
        },
        {
            text: 'Management',
            iconClass: 'fa fa-dashboard',
            items: [
                {
                    text: 'Users',
                    iconClass: 'fa fa-user',
                    link: '/users',
                },
                {
                    text: 'Roles',
                    iconClass: 'fa fa-user-plus',
                    link: '/users/roles',
                },
            ]
        }
    ];

## Form Components

### FormGroupWithErrors

This is an extension of FormGroup class which provides the additional public methods:

- Get control by name.

  getControl(name: string): AbstractControl;

- Sets errors by control names

  applyServerErrors(
  error: {title?: string, errors: {[key: string]: string[]}},
  form?: FromGroupWithErrors
  ): void;

* where form - target form class (default is **_this_** )

---

### General-Errors Component

This component shows the general errors for **FormGroup**. Provides a public method:

    setErrors(errors: string): void;

Used input parameters:

- **[form: FormGroup]** - FormGroup to set the general errors.

---

### FieldInput Component

#### Overview

Selector: **field-input**
Basically, this is extended angular FormControl Class, that shows **_input_** HTML Element with label and supports validators (like **_required_** etc.).

Used input parameters:

- **[labelKey: string]** - the text for label and input placeholder. This value will be translated by **_translate_** pipe inside (@ngx-translate package)
- **[fieldName: string]** - the name of input
- **[disabled: boolean]** - allows to dynamically control the disablement of an input field

This component may use only inside **_form-group_** directive.

#### Usage

    <field-input fieldName="userName" labelKey="Dto.UserName" required>

---

### NumberInput Component

#### Overview

Selector: **number-input**
Class extended of FieldInput Component for number inputs. It has all inputs and validators inherent to FieldInput. FormControl value for this input has number type. 

Additional input parameters:

- **[isPositive: boolean]** - allows to set only positive numbers (by default has _false_ value).

This component may use only inside **_form-group_** directive.

#### Usage

    <number-input fieldName="userName" labelKey="Dto.UserName" required>

---

### Debounce Directive

Selector: **[appDebouce]**

This directive is applicable to input elements.

This directive adds a delay and emits output Event **debounceKeyup** with input data.

Used input parameters:

- **debounceTime** - time to delay in **_ms_** (default is 500)

#### Usage

    <input appDebouce (debounceKeyup)="search($event.target.value)" />

# Services

## TranslateSettingsService

This service provides public methods for managing the current locale for an application.

### Public Methods Provided:

- **getLocales(): {name: string, code: string}** - returns a list of supported languages
- **getLocale(): string** - returns the current locale code
- **setLocale(locale: string): void** - sets input **locale** code as current and switch TranslateModule to current

---

## HttpService

This service provides public methods for get any content from server endpoint.

> ## Important Notice:
>
> This service require [AppToastrService](#apptoastrservice) to configure Library for **apiUrl** see the [Configure Library](#configure-library) section

### Standard Error Handling

All public methods provided by **HttpService** have standard error handling based on Http Status codes.

> ## Exceptional case:
>
> When the service receives a connection error then shows a toast message from the **HttpErrorResponse** class.

---

#### Error Handle Actions

| Http Status Code | Status Name           | Action                                                    |
| ---------------- | --------------------- | --------------------------------------------------------- |
| 401              | Unauthorised          | Shows toast message and navigate to **'home'** route      |
| 403              | Frobidden             | Shows toast message and navigate to **'forbidden'** route |
| 404              | NotFound              | Shows toast message and navigate to **'/'** route         |
| 500              | Internal Server Error | Show toast message and returns null                       |
| any              |                       | throws error                                              |

### Public Methods Provided:

- **get&lt;T&gt;(path: string): Promice&lt;T&gt;** - make a _*GET*_ request and return a response.
- **post&lt;T&gt;(path: string, data: T): Promice&lt;T&gt;** - make a _*POST*_ request with data and return a response.
- **put&lt;T&gt;(path: string, data: T): Promice&lt;T&gt;** - make a _*PUT*_ request with data and return a response.
- **delete(path: string): Promice&lt;object&gt;** - make a _*DELETE*_ request to endpoint and return a response.

> \*path - is target endpoint without a basic apiUrl part

---

## AppToastrService

This service provides a public methods to show toast messages.

> ## Important Notice:
>
> This service require to configure Library for default **toastrTimeOut** see the [Configure Library](#configure-library) section

### Public Methods Provided:

- **showError(message: string, title: string = 'Error'): void** - shows the stylized error message
- **showSuccess(message: string, title: string = ''): void** - shows the stylized success message

---

# Models

## AppSettings

> Type: _abstract class_

> Extends: -

> Description: The model for configuration [HttpService](#httpservice) and [AppToastrService](#apptoastrservice).

### Overview

| Prop name     | Required | Type   | Description                         |
| ------------- | -------- | ------ | ----------------------------------- |
| apiUrl        | yes      | string | The base endpoint server url        |
| accountUrl    | yes      | string | The url to account server           |
| toastrTimeOut | yes      | number | Timeout to auto close toast message |

---

## CustomHttpErrorResponse

> Type: _declare class_

> Extends: HttpErrorResponse (from @angular/common/http)

> Description: Add title property to HttpErrorResponse Type.

### Overview

| Prop name | Required | Type   | Description |
| --------- | -------- | ------ | ----------- |
| title     | yes      | string | The title   |

---

## CustomHttpErrorResponse

> Type: _enum_

> Extends: -

> Description: Enum for http codes.

### Overview

| Key                 | Value |
| ------------------- | ----- |
| BadRequest          | 400   |
| Forbidden           | 403   |
| InternalServerError | 500   |
| NotFound            | 404   |
| OK                  | 200   |
| Unauthorized        | 401   |

---

## HttpMethods

> Type: _const_ : [NamedModel[]](#namedmodel)

> Extends: -

> Description: - .

### Overview

| id     | name   |
| ------ | ------ |
| POST   | POST   |
| PUT    | PUT    |
| GET    | GET    |
| DELETE | DELETE |

---

## IdentifiedModel

> Type: _interface_

> Extends: -

> Description: Declare _id_ field.

### Overview

| Prop Name | Required | Type   |
| --------- | -------- | ------ |
| id        | yes      | string |

---

## NamedModel

> Type: _interface_

> Extends: [IdentifiedModel](#identifiedmodel)

> Description: Declare _id_ and _name_ fields.

### Overview

| Prop Name | Required | Type   |
| --------- | -------- | ------ |
| id        | yes      | string |
| name      | yes      | string |

---

## IndiginaConfiguration

> Type: _abstract class_

> Extends: -

> Description: Interface for configuration @indigina/angular library.

### Overview

| Prop Name | Required | Type                        | Description                        |
| --------- | -------- | --------------------------- | ---------------------------------- |
| langs     | no       | TranslateLoader             | Configuration for Translate Module |
| name      | no       | [AppSettings](#appsettings) | Basic application environment      |

---

## Language

> Type: _interface_

> Extends: -

> Description: -

### Overview

| Prop Name | Required | Type   | Description         |
| --------- | -------- | ------ | ------------------- |
| name      | yes      | string | Language name       |
| code      | yes      | string | Language identifier |

---

# Provided packages

- [@angular/platform-browser/animations](https://angular.io/api/platform-browser/animations)
- [@ngx-translate/core](https://www.npmjs.com/package/@ngx-translate/core)
- [ngx-clipboard](https://www.npmjs.com/package/ngx-clipboard)
- [ngx-toastr](https://www.npmjs.com/package/ngx-toastr)