angular-package / core

Core features.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Packages

Useful and simple to use packages based on the angular.io.

Package Description Status
change-detection Improve application performance. npm version
core Core features. npm version
prism Prism highlighter module. npm version
property Features to handle object properties. npm version
reactive Automatize process of creating some rxjs features. npm version
ui User interface. In Progress
type Common types, type guards and type checkers. npm version
testing Support for testing other packages. npm version

Click on the package name to visit the package.

angular-package/core

Core features.

npm version

GitHub issues GitHub forks GitHub stars GitHub license

GitHub sponsors Support me on Patreon


Table of contents



Basic concepts

Checks

It's to check the provided value to be the same as expected.

Type guard (constrain)

Constrains the parameter type to not let input unexpected value in the code editor.

Guards

It's a combination of both above, constrains the type of the parameter in the code editor, and checks its provided argument.

Sets

Sets the given value in the object.

Defines

Returns defined value from the method, instead of storing it in the object.


Skeleton

This package was built by the library skeleton which was generated with Angular CLI version 12.1.1.

Copy this package to the packages/core folder of the library skeleton then run the commands below.

Build

Run ng build core to build the package. The build artifacts will be stored in the dist/ directory.

Running unit tests

Run ng test core to execute the unit tests via Karma.


Installation

Install @angular-package/core package with command:

npm i --save @angular-package/core

Api

/**
 * Callback
 * --------
 * @angular-package/core/callback
 */
import {
  // Class.
  Callback,
} from '@angular-package/core';
/**
 * Component loader.
 * --------
 * @angular-package/core/component-loader
 */
import {
  // Class.
  ComponentLoader,
} from '@angular-package/core';
/**
 * Error
 * -----
 * @angular-package/core/error
 */
import {
  // Class.
  ValidationError,
  // Interface.
  ErrorMessage,
} from '@angular-package/core';

Callback

/**
 * Callback
 * --------
 * @angular-package/core/callback
 */
import {
  // Class.
  Callback,
} from '@angular-package/core';

Callback

Manages the callback function of a ResultCallback type.


Static methods:

Methods Description
Callback.defineCallback() Defines the function of a ResultCallback type that contains a ResultHandler function to handle the result and the provided value of its check
Callback.defineErrorCallback() Defines the function of ResultCallback type to throw ValidationError with a specified message on a state from the throwOnState
Callback.guard() Guards the provided resultCallback to be ResultCallback type
Callback.isCallback() Checks if the provided value is an instance of Callback with optional indicating allowed names under which callback functions can be stored

Constructor:

Constructor Description
Callback() Initialize an instance of a Callback with the allowed names under which callback functions can be stored

Instance methods:

Callback.prototype. Description
getCallback() Gets from the storage specified by-name callback function of a ResultCallback type
setCallback() Sets the callback function of a ResultCallback type to the storage under the given allowed name restricted by AllowNames
setErrorCallback() Sets a function of a ResultCallback type to the storage under the given allowed name with the given error message to throw on the specified state from the throwOnState

Callback static methods


Callback.defineCallback()

Defines the function of a ResultCallback type that contains a ResultHandler function to handle the result and the provided value of its check.

static defineCallback(
  resultHandler: ResultHandler
): ResultCallback {
  return (result: boolean, value: any) => {
    if (is.function(resultHandler)) {
      resultHandler(result, value);
    }
    return result;
  };
}

Parameters:

Name: type Description
resultHandler: ResultHandler The function of ResultHandler type to handle the value and the result of the check

Returns:

Returns Type Description
ResultCallback Function The return type is a function of a ResultCallback type

The return value is a function of a ResultCallback type that contains a function of ResultHandler.

Usage:

// Example usage.
import { Callback } from '@angular-package/core';
import { is } from '@angular-package/type';

const stringCallback = Callback.defineCallback(
  (result: boolean, value: any) => {
    if (is.false(result)) {
      console.log(`Something went wrong`);
    }
  }
);

is.string(5, stringCallback);

Callback.defineErrorCallback()

Defines the function of ResultCallback type to throw ValidationError with a specified message on a state from the throwOnState.

static defineErrorCallback(
  message: string | ErrorMessage,
  throwOnState: boolean = false
): ResultCallback {
  return Callback.defineCallback((result: boolean, value: any): void => {
    if (is.false(throwOnState) ? is.false(result) : is.true(result)) {
      throw new ValidationError(message);
    }
  });
}

Parameters:

Name: type Description
message: string | ErrorMessage The message of string type or ErrorMessage interface, to throw with an error of ValidationError
throwOnState: boolean A state of boolean type on which an error of ValidationError should be thrown. By default, it's set to false

Returns:

Returns Type Description
ResultCallback Function The return type is a function of a ResultCallback type

The return value is a function of a ResultCallback type that throws a ValidationError on a specified state.

Usage:

// Example usage.
import { Callback } from '@angular-package/core';
import { is } from '@angular-package/type';

const stringCallback = Callback.defineErrorCallback('Something went wrong');
is.string(5, stringCallback); // Throws ValidationError: Something went wrong

Callback.guard()

Guards the provided resultCallback to be ResultCallback type.

static guard(
  resultCallback: ResultCallback
): resultCallback is ResultCallback {
  return guard.function(resultCallback);
}

Parameters:

Name: type Description
resultCallback: ResultCallback The function of ResultCallback, to guard

Returns:

Returns Type Description
resultCallback is ResultCallback boolean The return type is boolean, as the result of its statement that indicates the provided resultCallback is the function of a ResultCallback type

The return value is a boolean indicating whether the provided resultCallback parameter is a function.

Usage:

// Example usage.
import { Callback } from '@angular-package/core';

Callback.guard(result => result); // Returns `true`.
Callback.guard({} as any); // Returns `false`.

Callback.isCallback()

Checks if the provided value is an instance of Callback with optional indicating allowed names under which callback functions can be stored

static isCallback<AllowNames extends string>(
  value: any,
  ...allowNames: AllowNames[]
): value is Callback<AllowNames> {
  return is.instance(value, Callback);
}

Generic type variables:

Name Description
AllowNames extends string A generic variable of AllowNames name that is constrained by the string type and is used to indicate allowed names under which callback functions can be stored, and is linked with the return type value is Callback<AllowNames>. By default, its value is captured from the provided allowNames rest parameter

Parameters:

Name: type Description
value: any The value of any type to check
...allowNames: AllowNames[] A rest parameter of AllowNames that indicates allowed names for the Callback<AllowNames> return type

Returns:

Returns Type Description
value is Callback<AllowNames> boolean The return type is boolean, as the result of its statement that indicates the provided value is a Callback with allowed names from the provided allowNames parameter or generic variable AllowNames

The return value is a boolean indicating whether the value is an instance of Callback .

Usage:

// Example usage.
import { Callback } from '@angular-package/core';

Callback.isCallback({}); // Returns `false`
Callback.isCallback(new Callback()); // Returns `true`

const callback = new Callback('one', 'two', 'three');
if (Callback.isCallback(callback)) {
  callback.setCallback('one', result => result); // There's no hint on `name` parameter about allowed names.
}
if (Callback.isCallback(callback, 'one', 'two')) {
  callback.setCallback('one', result => result); // There is a hint from the provided `allowNames` parameter of the `isCallback()` method.
}

Callback constructor


Callback()

Initialize an instance of a Callback with the allowed names under which callback functions can be stored.

new Callback<AllowNames extends string>(...allowNames: AllowNames[]) {
  this.#allowedNames = guard.array(allowNames)
    ? new Set(allowNames)
    : this.#allowedNames;
}

Generic type variables:

Name Description
AllowedNames extends string A generic variable AllowNames that is constrained by the string type and is used to restrict allowed names under which callback functions can be stored. By default, its value is captured from the provided allowNames rest parameter

Parameters:

Name: type Description
allowNames: AllowedNames[] A rest parameter of a string type allowed names under which callback functions can be stored. Only those names given by this parameter are being checked by the isNameAllowed() private method

Returns:

The return value is new instance of a Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/core';

const callback = new Callback(['set', 'define']);

Callback instance methods


Callback.prototype.getCallback()

Gets from the storage specified by-name callback function of a ResultCallback type.

public getCallback<Name extends AllowNames>(
  name: Name
): Pick<CallbackStorage, Name>[Name] {
  return this.#storage.get(name);
}

Generic type variables:

Name Description
Name extends AllowNames A generic Name variable constrained by the AllowNames indicates the name under which callback function is picked from the storage. It is linked with the return type Pick<CallbackStorage, Name>[Name] that refers exactly to the type, which is ResultCallback of the callback function picked from the storage with the provided name. By default, its value is captured from the provided name

Parameters:

Name: type Description
name: Name A string type name that is restricted by the AllowNames to pick stored callback function

Returns:

Returns Type Description
Pick<CallbackStorage, Name>[Name] function The return type is a ResultCallback function that is picked from the stored callback function of the given name

The return value is the callback function of a ResultCallback type picked from the storage.

Usage:

// Example usage.
import { Callback } from '@angular-package/core';
/**
 * Initialize `Callback`.
 */
const callback = new Callback('firstName');

callback
  .setCallback('firstName', result => result) // Set the callback function under the given name.
  .getCallback('firstName'); // Get the function stored under the given name.

Callback.prototype.setCallback()

Sets the callback function of a ResultCallback type to the storage under the given allowed name restricted by AllowNames.

public setCallback<Name extends AllowNames>(
  name: Name,
  resultHandler: ResultHandler
): this {
  if (this.isNameAllowed(name)) {
    this.#storage.set(name, Callback.defineCallback(resultHandler));
  }
  return this;
}

Generic type variables:

Name Description
Name extends AllowNames A generic Name variable constrained by the AllowNames indicates the name under which callback function is stored. By default, its value is captured from the provided name

Parameters:

Name: type Description
name: Name A string type name that is restricted by the AllowNames under which the function is stored. The allowed status of the provided name is checked by the private method isNameAllowed()
resultHandler: ResultHandler The function of ResultHandler to handle the result of the ResultCallback function before its result returns

Returns:

Returns Type Description
this object The return type is an instance of Callback

The return value is an instance of Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/core';
/**
 * Initialize `Callback`.
 */
const callback = new Callback('firstName');

callback
  .setCallback('firstName', result => result) // Set the callback function under the given name.

Callback.prototype.setErrorCallback

Sets a function of a ResultCallback type to the storage under the given allowed name with the given error message to throw on the specified state from the throwOnState.

public setErrorCallback<Name extends AllowNames>(
  name: Name,
  message: string | ErrorMessage,
  throwOnState: boolean = false
): this {
  this.setCallback(name, Callback.defineErrorCallback(message, throwOnState));
  return this;
}

Generic type variables:

Name Description
Name extends AllowNames A generic Name variable constrained by the AllowNames indicates the name under which callback function is stored. By default, its value is captured from the provided name

Parameters:

Name: type Description
name: Name A string type name that is restricted by the AllowNames under which the function is stored. The allowed status of the provided name is checked by the private method isNameAllowed()
message: string | ErrorMessage The message of string type or ErrorMessage interface, to throw with an error of ValidationError
throwOnState: boolean A state of boolean type on which an error of ValidationError should be thrown. By default, it's set to false

Returns:

Returns Type Description
this object The return type is an instance of Callback

The return value is an instance of Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/core';
/**
 * Initialize `Callback`.
 */
const callback = new Callback('firstName', 'lastName');

callback
  .setErrorCallback('lastName', 'LastName must be a string type', false); // Set the error callback function under the given name.

Component loader

ComponentLoader

Abstract class to handle Angular API for loading components dynamically.


Static methods:

Method Description
ComponentLoader.isContainer() Checks if the provided value is a ViewContainerRef type
ComponentLoader.isFactoryResolver() Checks if any value is a ComponentFactoryResolver by checking properties in prototype against the resolveComponentFactory

Constructor:

Constructor Description
ComponentLoader() Creates an instance with initializing ComponentFactoryResolver

Instance methods:

ComponentLoader.prototype. Description
assignProperties() Assigns the whole object or its properties indicated by the provided keys to the dynamic component
createComponent() Creates component from the provided component or the stored factory, and loads its host view into the existing container
destroyComponent() Destroys the existing component, all of the data structures associated with it, and clears the container. The status of destroying component result is stored in the created property, and it's false when component was successfully destroyed
getProperty() Gets the value of the property indicated by the provided key from the dynamic component
isCreated() Checks if the dynamic component is created by using the method createComponent(). The result of the check is stored in the created property
setContainer() Sets the provided container of a ViewContainerRef when its property _hostLView is found
setFactory() Sets the factory object based on the provided component of a class type
setProperty() Sets the value of a property indicated by the provided key of an instance of a DynamicComponent

ComponentLoader instance properties


ComponentLoader.prototype.component

Returns privately stores component created by a createComponent() method.

public get component(): ComponentRef<DynamicComponent> | undefined {
  return this.#component;
}

ComponentLoader.prototype.created

Returns the creation state of a dynamic component.

public get created(): boolean {
  return this.$created;
}

ComponentLoader.prototype.instance

Returns an instance of the created dynamic component.

public get instance(): DynamicComponent | undefined {
  return this.#component?.instance;
}

ComponentLoader static methods


ComponentLoader.isContainer()

Checks if the provided value is a ViewContainerRef type.

static isContainer(
  value: any,
  callback?: ResultCallback
): value is ViewContainerRef {
  return is.objectKey(value, '_hostLView', callback);
}

Parameters:

Name: type Description
value: any The value of any type to check
callback?: ResultCallback An optional ResultCallback function to handle the result of the check

Returns:

Returns Type Description
value is ViewContainerRef boolean The return type is boolean, as the result of its statement that indicates the provided value is ViewContainerRef

The return value is a boolean indicating whether the value is a container of ViewContainerRef.

Usage:

// Example usage.
import { Component, ViewChild, ViewContainerRef, AfterViewInit } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: '<div #newContainer></div>',
})
export class ExampleComponent implements AfterViewInit {
  @ViewChild('newContainer', { read: ViewContainerRef }) container: any;

  ngAfterViewInit(): void {
    ComponentLoader.isContainer(this.container);
  }
}

ComponentLoader.isFactoryResolver()

Checks if any value is a ComponentFactoryResolver by checking properties in prototype against the resolveComponentFactory.

static isFactoryResolver(
  value: any,
  callback?: ResultCallback
): value is ComponentFactoryResolver {
  return is.objectKeyIn(value, 'resolveComponentFactory', callback);
}

Parameters:

Name: type Description
value: any The value of any type to check
callback?: ResultCallback An optional ResultCallback function to handle the result of the check

Returns:

Returns Type Description
value is ComponentFactoryResolver boolean The return type is boolean, as the result of its statement that indicates the provided value is a ComponentFactoryResolver

The return value is a boolean indicating whether the value is ComponentFactoryResolver.

Usage:

// Example usage.
import { Component, ComponentFactoryResolver } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: ''
})
export class ExampleComponent {
  constructor(
    factoryResolver: ComponentFactoryResolver
  ) {
    ComponentLoader.isFactoryResolver(factoryResolver);
  }
}

ComponentLoader constructor


Creates an instance with initializing ComponentFactoryResolver.

constructor(
  protected factoryResolver: ComponentFactoryResolver,
  callback?: (callback: Callback<
    | 'getProperty'
    | 'isContainer'
    | 'isCreated'
    | 'isFactoryResolver'
    | 'setContainer'
    | 'setFactory'
    | 'setProperty'
  >) => void
) {
  // Checks the existence of a `ComponentFactoryResolver`. Needed when extends component.
  ComponentLoader.isFactoryResolver(
    factoryResolver,
    this.#callback.getCallback('isFactoryResolver')
  );
  if (is.function(callback)) {
    callback(this.#callback);
  }
}

Parameters:

Name: type Description
factoryResolver: ComponentFactoryResolver The required value of a ComponentFactoryResolver as a base for retrieving component factories
callback?: Callback<| 'getProperty' | 'isContainer' | 'isCreated' | 'isFactoryResolver' | 'setContainer' | 'setFactory' | 'setProperty' >

Throws:

Throws an Error when ComponentFactoryResolver is not defined.

Returns:

The return value is an instance of a child class.

Usage:

// Example usage.
import { Component, ComponentFactoryResolver } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: ''
})
export class ExampleComponent extends ComponentLoader {
  constructor(
    factoryResolver: ComponentFactoryResolver
  ) {
    super(factoryResolver);
  }
}

ComponentLoader instance methods


ComponentLoader.prototype.assignProperties()

Assigns the whole object or its properties indicated by the provided keys to the dynamic component

public assignProperties<
  Obj extends object,
  Key extends keyof DynamicComponent
>(object: Obj, ...keys: Key[]): this {
  if (guard.object(object) && guard.array(keys) && keys.length > 0) {
    keys.forEach((key) => {
      Object.assign(this.instance, {
        [key]: object[key as string as keyof Obj],
      });
    });
  } else {
    Object.assign(this.instance, object);
  }
  return this;
}

Generic type variables:

Name Description
Obj extends object A generic Obj variable that is guarded by the object type and is used by the provided obj from which it captures the default value
Key extends keyof DynamicComponent A generic Key variable that is constrained by the key of the provided DynamicComponent and is used by the keys rest parameter to indicate which properties values assign from the provided Obj

Parameters:

Name: type Description
object: Obj An object to assign its properties to the dynamic component
...keys: Key[] A rest parameter of property names from the dynamic component to assign from the provided obj

Returns:

The return value is an instance of a child class.

Usage:

// Example usage.
import { Component, ViewChild, ViewContainerRef, AfterViewInit, ComponentFactoryResolver } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: `Dynamic component created successfully`
})
export class DynamicComponent {
  firstName = '';
}

@Component({
  template: '<div #newContainer></div>',
})
export class ExampleComponent extends ComponentLoader<DynamicComponent> implements AfterViewInit {
  @ViewChild('newContainer', { read: ViewContainerRef }) container: any;

  constructor(public factoryResolver: ComponentFactoryResolver) {
    super(factoryResolver);
  }

  ngAfterViewInit(): void {
    this
      .createComponent(DynamicComponent, this.container)
      .assignProperties({
        firstName: 'My first name'
      }, 'firstName');
    console.log(this.instance?.firstName); // Returns 'My first name'
  }
}

ComponentLoader.prototype.createComponent()

Creates component from the provided component or the stored factory, and loads its host view into the existing container.

public createComponent(
  component?: Type<DynamicComponent>,
  container: ViewContainerRef = this.#container,
  callback: ResultCallback = this.#callback.getCallback('createComponent')
): this {
  if (
    ComponentLoader.isContainer(
      container,
      this.#callback.getCallback('isContainer')
    )
  ) {
    if (is.false(this.isCreated())) {
      if (is.class(component)) {
        // Creates component by using the provided `component`.
        this.#component = container.createComponent(
          this.factoryResolver.resolveComponentFactory(component)
        );
      } else if (is.object(this.#factory)) {
        // Creates component from the stored factory by the method `setFactory()`.
        this.#component = container.createComponent(this.#factory);
      }
      // Stores the result of the component creation.
      this.$created = this.isCreated(callback);
    }
  }
  return this;
}

Parameters:

Name: type Description
component?: Type<DynamicComponent> An optional class of a DynamicComponent type
container: ViewContainerRef A container of ViewContainerRef type to load component host view to it
callback?: ResultCallback An optional ResultCallback function to handle the result of the check is component created

Returns:

The return value is an instance of a child class.

Usage:

// Example usage.
import { Component, ViewChild, ViewContainerRef, AfterViewInit, ComponentFactoryResolver } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: `Dynamic component created successfully`
})
export class DynamicComponent {}

@Component({
  template: '<div #newContainer></div>',
})
export class ExampleComponent extends ComponentLoader<DynamicComponent> implements AfterViewInit {
  @ViewChild('newContainer', { read: ViewContainerRef }) container: any;

  constructor(public factoryResolver: ComponentFactoryResolver) {
    super(factoryResolver);
  }

  ngAfterViewInit(): void {
    this.createComponent(DynamicComponent, this.container);
  }
}

ComponentLoader.prototype.destroyComponent()

Destroys the existing component, all of the data structures associated with it, and clears the container. The status of destroying component result is stored in the created property, and it's false when component was successfully destroyed.

public destroyComponent(
  callback?: ResultCallback
): ComponentRef<DynamicComponent> | undefined {
  if (this.isCreated()) {
    // "Destroys the component instance and all of the data structures associated with it."
    this.#component?.destroy();
    this.#component = undefined;
  }
  if (is.object(this.#container)) {
    // "Destroys all views in this container."
    this.#container.clear();
  }
  // Stores the result of destroying the component. Should be `false`.
  this.$created = is.undefined(this.#component, callback);
  // The return value should be `undefined`.
  return this.#component;
}

Parameters:

Name: type Description
callback?: ResultCallback An optional ResultCallback function to handle the result of the check whether a dynamic component is successfully destroyed

Returns:

The return value is undefined if the method successfully destroyed a privately stored component, or it's a component created by a ComponentFactory.

Usage:

// Example usage.
import { Component, ViewChild, ViewContainerRef, AfterViewInit, ComponentFactoryResolver } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: `Dynamic component created successfully`
})
export class DynamicComponent {}

@Component({
  template: '<div #newContainer></div>',
})
export class ExampleComponent extends ComponentLoader<DynamicComponent> implements AfterViewInit {
  @ViewChild('newContainer', { read: ViewContainerRef }) container: any;

  constructor(public factoryResolver: ComponentFactoryResolver) {
    super(factoryResolver);
  }

  ngAfterViewInit(): void {
    // Creates dynamic component.
    this.createComponent(DynamicComponent, this.container);

    setTimeout(() => {
      // Destroys dynamic component.
      this.destroyComponent();
    }, 3000);
  }
}

ComponentLoader.prototype.getProperty()

Gets the value of the property indicated by the provided key from the dynamic component.

public getProperty<Key extends keyof DynamicComponent>(
  key: Key,
  callback: ResultCallback = this.#callback.getCallback('getProperty')
): DynamicComponent[Key] | undefined {
  if (is.objectKeyIn(this.instance, key, callback)) {
    return this.instance[key];
  }
  return;
}

Generic type variables:

Name Description
Key extends keyof DynamicComponent A generic Key variable that is constrained by the key of the provided DynamicComponent and is used by the key parameter to indicate which property value get from the dynamic component instance

Parameters:

Name: type Description
key: Key The key of an instance of a DynamicComponent to get the property value. The value is being checked against the proper key and its existence in the instance of a dynamic component
callback: ResultCallback The function of a ResultCallback type to handle the result of the check whether the dynamic component exists, with its property from the provided key. By default, it uses an internal callback

Throws:

The method throws an error if the dynamic component is not created or it is created, but it has not a property of the specified key.

Returns:

The return value is the value of the indicated property from the instance of a dynamic component.

Usage:

// Example usage.
import { Component, ViewChild, ViewContainerRef, AfterViewInit, ComponentFactoryResolver } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: `Dynamic component created successfully`
})
export class DynamicComponent {
  firstName = 'My first name';
}

@Component({
  template: '<div #newContainer></div>',
})
export class ExampleComponent extends ComponentLoader<DynamicComponent> implements AfterViewInit {
  @ViewChild('newContainer', { read: ViewContainerRef }) container: any;

  constructor(public factoryResolver: ComponentFactoryResolver) {
    super(factoryResolver);
  }

  ngAfterViewInit(): void {
    this
      .createComponent(DynamicComponent, this.container);

    console.log(this.getProperty('firstName')); // Returns 'My first name'
  }
}

ComponentLoader.prototype.isCreated()

Checks if the dynamic component is created by using the method createComponent(). The result of the check is stored in the created property.

public isCreated(callback?: ResultCallback): boolean {
  return is.object(this.#component, callback);
}

Parameters:

Name: type Description
callback?: ResultCallback An optional function of a ResultCallback type to handle the result of the check whether a dynamic component is already created

Returns:

The return value is a boolean indicating whether the dynamic component is already created.

Usage:

// Example usage.
import { Component, ViewChild, ViewContainerRef, AfterViewInit, ComponentFactoryResolver } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: `Dynamic component created successfully`
})
export class DynamicComponent {}

@Component({
  template: '<div #newContainer></div>',
})
export class ExampleComponent extends ComponentLoader<DynamicComponent> implements AfterViewInit {
  @ViewChild('newContainer', { read: ViewContainerRef }) container: any;

  constructor(public factoryResolver: ComponentFactoryResolver) {
    super(factoryResolver);
  }

  ngAfterViewInit(): void {
    this.createComponent(this.container, DynamicComponent);
    console.log(this.isCreated()); // Returns `true`.
  }
}

ComponentLoader.prototype.setContainer()

Sets the provided container of a ViewContainerRef when its property _hostLView is found.

public setContainer(
  container: ViewContainerRef,
  callback: ResultCallback = this.#callback.getCallback('setContainer')
): this {
  if (ComponentLoader.isContainer(container, callback)) {
    this.#container = container;
  }
  return this;
}

Parameters:

Name: type Description
container: ViewContainerRef The value of a class type to retrieve the factory object
callback: ResultCallback An optional function of a ResultCallback type to handle the result of the check whether a dynamic component is already created

Returns:

The return value is an instance of a child class.

Usage:

// Example usage.
import { Component, ViewChild, ViewContainerRef, AfterViewInit, ComponentFactoryResolver } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: `Dynamic component created successfully`
})
export class DynamicComponent {}

@Component({
  template: '<div #newContainer></div>',
})
export class ExampleComponent extends ComponentLoader<DynamicComponent> implements AfterViewInit {
  @ViewChild('newContainer', { read: ViewContainerRef }) container: any;

  constructor(public factoryResolver: ComponentFactoryResolver) {
    super(factoryResolver);
  }

  ngAfterViewInit(): void {
    this
      .setContainer(this.container) // Sets the container.
      .createComponent(DynamicComponent); // Creates the component.
  }
}

ComponentLoader.prototype.setFactory()

Sets the factory object based on the provided component.

public setFactory(
  component: Type<DynamicComponent>,
  callback: ResultCallback = this.#callback.getCallback('setFactory')
): this {
  if (guard.class(component, callback)) {
    this.#factory = this.factoryResolver.resolveComponentFactory(component);
  }
  return this;
}

Parameters:

Name: type Description
component: Type<DynamicComponent> Class of a DynamicComponent type to retrieve the factory object
callback: ResultCallback An optional function of a ResultCallback type to handle the result of the check whether a dynamic component is already created

Returns:

The return value is an instance of a child class.

Usage:

// Example usage.
import { Component, ViewChild, ViewContainerRef, AfterViewInit, ComponentFactoryResolver } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: `Dynamic component created successfully`
})
export class DynamicComponent {}

@Component({
  template: '<div #newContainer></div>',
})
export class ExampleComponent extends ComponentLoader<DynamicComponent> implements AfterViewInit {
  @ViewChild('newContainer', { read: ViewContainerRef }) container: any;

  constructor(public factoryResolver: ComponentFactoryResolver) {
    super(factoryResolver);
  }

  ngAfterViewInit(): void {
    this
      .setContainer(this.container) // Sets the container.
      .setFactory(DynamicComponent) // Sets the factory.
      .createComponent(); // Creates the component.
  }
}

ComponentLoader.prototype.setProperty()

Sets the value of a property indicated by the provided key of an instance of DynamicComponent.

public setProperty<Key extends keyof DynamicComponent>(
  key: Key,
  value: DynamicComponent[Key],
  callback: ResultCallback = this.#callback.getCallback('setProperty')
): this {
  if (is.objectKeyIn(this.instance, key, callback)) {
    this.instance[key] = value;
  }
  return this;
}

Generic type variables:

Name Description
Key extends keyof DynamicComponent A generic Key variable that is constrained by the key of the provided DynamicComponent and is used by the key parameter to indicate which property value get from the dynamic component instance

Parameters:

Name: type Description
key: Key The key of a property from the instance of a DynamicComponent to set its value
value: DynamicComponent[Key] The value of a captured type from the property of DynamicComponent instance to set
callback: ResultCallback The function of a ResultCallback type to handle the result of the check whether the dynamic component exists, with its property from the provided key. By default, it uses an internal callback

Throws:

The method throws an error if the dynamic component is not created or it is created, but it has not a property of the specified key.

Returns:

The return value is an instance of a child class.

Usage:

// Example usage.
import { Component, ViewChild, ViewContainerRef, AfterViewInit, ComponentFactoryResolver } from '@angular/core';
import { ComponentLoader } from '@angular-package/core';

@Component({
  template: `Dynamic component created successfully`
})
export class DynamicComponent {
  firstName = '';
}

@Component({
  template: '<div #newContainer></div>',
})
export class ExampleComponent extends ComponentLoader<DynamicComponent> implements AfterViewInit {
  @ViewChild('newContainer', { read: ViewContainerRef }) container: any;

  constructor(public factoryResolver: ComponentFactoryResolver) {
    super(factoryResolver);
  }

  ngAfterViewInit(): void {
    this
      .createComponent(DynamicComponent, this.container)
      .setProperty('firstName', 'My first name');
    console.log(this.instance?.firstName); // Returns 'My first name'
  }
}

Error

/**
 * Error
 * -----
 * @angular-package/core/error
 */
import {
  // Class.
  ValidationError,
  // Interface.
  ErrorMessage,
} from '@angular-package/core';

ValidationError

Manages an Error of the validation.

Static methods:

Methods Description
ValidationError.defineMessage() Defines the error message of a string type from the provided message of an object

Constructor:

Constructor Description
ValidationError() Creates a new instance with the message. If the provided message is an object, then its properties are assigned to the instance

ValidationError static properties


ValidationError.template

Template of the error message with the replaceable [problem] and [fix].

static template = `Problem: [problem] => Fix: [fix]`;

ValidationError instance public properties


ValidationError.prototype.fix

A possible solution to the described problem of a string type. By default, it's an empty string.

public fix = '';

ValidationError.prototype.name

Error name of a string type that is being thrown. By default, it's ValidationError.

public name = ValidationError.name;

ValidationError.prototype.problem

The validation problem of a string type. By default, it's an empty string.

public problem = '';

ValidationError static methods


ValidationError.defineMessage()

Defines the validation error message of a string type from the provided message of the ErrorMessage interface.

static defineMessage(message: ErrorMessage): string {
  if (is.objectKey(message, ['fix', 'problem'])) {
    return `Problem: ${message.problem}. ${
        is.string(message.fix) ? `Fix: ${message.fix}` : ''
      }`;
  }
  return '';
}

Parameters:

Name: type Description
message: ErrorMessage An object of the ErrorMessage interface to build a message of a string type. The value is checked against the proper object

Returns:

The return value is a message of a string type created from the provided message of ErrorMessage interface, or it's an empty string if the provided message object isn't proper.

Usage:

// Example usage.
import { ValidationError } from '@angular-package/core';

const fix = 'There is no solution to the described problem.';
const problem = 'The problem has no solution.';
/**
 * Returns
 * --------
 * Problem: The problem has no solution. => Fix: There is no solution to the described problem.
 */
const errorMessage = ValidationError.defineMessage({ fix, problem });

ValidationError constructor


ValidationError()

Creates a new instance with the message. If the provided message is an object, then its properties are assigned to the instance.

new ValidationError(message: string | ErrorMessage) {
  super(is.string(message) ? message : ValidationError.defineMessage(message));
  if (is.object(message)) {
    Object.assign(this, getProperties(message, ['fix', 'problem']));
  }
}

Parameters:

Name: type Description
message: string | ErrorMessage The message of a string type or of an ErrorMessage interface that is used to throw with an error

Returns:

The return value is an instance of ValidationError.

Usage:

// Example usage.
import { ValidationError } from '@angular-package/core';

const fix = 'There is no solution to the described problem.';
const problem = 'The problem has no solution.';
const validationError = new ValidationError({ fix, problem });

Interface

ErrorMessage

The shape of an object for an error message that contains a possible solution to the described problem.

interface ErrorMessage {
  /**
   * Possible solution to the described problem of a `string` type.
   */
  fix: string;
  /**
   * Error problem of a `string` type.
   */
  problem: string;
}

ResultHandler

Function to handle the result of the ResultCallback function before its result returns.

type ResultHandler = (result: boolean, value: any) => void;

GIT

Commit

Versioning

Semantic Versioning 2.0.0

Given a version number MAJOR.MINOR.PATCH, increment the:

  • MAJOR version when you make incompatible API changes,
  • MINOR version when you add functionality in a backwards-compatible manner, and
  • PATCH version when you make backwards-compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

FAQ How should I deal with revisions in the 0.y.z initial development phase?

The simplest thing to do is start your initial development release at 0.1.0 and then increment the minor version for each subsequent release.

How do I know when to release 1.0.0?

If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backwards compatibility, you should probably already be 1.0.0.

License

MIT © angular-package (license)

About

Core features.

License:MIT License


Languages

Language:TypeScript 96.5%Language:JavaScript 3.5%