Skip to content

Repository files navigation

Packages

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

PackageDescriptionStatus
change-detectionImprove application performance.npm version
coreCore features.npm version
prismPrism highlighter module.npm version
propertyFeatures to handle object properties.npm version
reactiveAutomatize process of creating some rxjs features.npm version
uiUser interface.In Progress
typeCommon types, type guards and type checkers.npm version
testingSupport for testing other packages.npm version

Click on the package name to visit the package.

angular-package/core

Core features.

npm version

GitHub issuesGitHub forksGitHub starsGitHub license

GitHub sponsorsSupport 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:

MethodsDescription
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:

ConstructorDescription
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.

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

Parameters:

Name: typeDescription
resultHandler: ResultHandlerThe function of ResultHandler type to handle the value and the result of the check

Returns:

ReturnsTypeDescription
ResultCallbackFunctionThe 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';conststringCallback=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.

staticdefineErrorCallback(message: string|ErrorMessage,throwOnState: boolean=false): ResultCallback{returnCallback.defineCallback((result: boolean,value: any): void=>{if(is.false(throwOnState) ? is.false(result) : is.true(result)){thrownewValidationError(message);}});}

Parameters:

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

Returns:

ReturnsTypeDescription
ResultCallbackFunctionThe 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';conststringCallback=Callback.defineErrorCallback('Something went wrong');is.string(5,stringCallback);// Throws ValidationError: Something went wrong

Callback.guard()

Guards the provided resultCallback to be ResultCallback type.

staticguard(resultCallback: ResultCallback): resultCallback is ResultCallback{returnguard.function(resultCallback);}

Parameters:

Name: typeDescription
resultCallback: ResultCallbackThe function of ResultCallback, to guard

Returns:

ReturnsTypeDescription
resultCallback is ResultCallbackbooleanThe 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({}asany);// 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

staticisCallback<AllowNamesextendsstring>(value: any,
...allowNames: AllowNames[]): valueisCallback<AllowNames>{returnis.instance(value,Callback);}

Generic type variables:

NameDescription
AllowNames extends stringA 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: typeDescription
value: anyThe value of any type to check
...allowNames: AllowNames[]A rest parameter of AllowNames that indicates allowed names for the Callback<AllowNames> return type

Returns:

ReturnsTypeDescription
value is Callback<AllowNames>booleanThe 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(newCallback());// Returns `true`constcallback=newCallback('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.

newCallback<AllowNamesextendsstring>(...allowNames: AllowNames[]){this.#allowedNames =guard.array(allowNames)
? newSet(allowNames)
: this.#allowedNames;}

Generic type variables:

NameDescription
AllowedNames extends stringA 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: typeDescription
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';constcallback=newCallback(['set','define']);

Callback instance methods


Callback.prototype.getCallback()

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

publicgetCallback<NameextendsAllowNames>(name: Name): Pick<CallbackStorage,Name>[Name]{returnthis.#storage.get(name);}

Generic type variables:

NameDescription
Name extends AllowNamesA 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: typeDescription
name: NameA string type name that is restricted by the AllowNames to pick stored callback function

Returns:

ReturnsTypeDescription
Pick<CallbackStorage, Name>[Name]functionThe return type is a ResultCallbackfunction 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`. */constcallback=newCallback('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.

publicsetCallback<NameextendsAllowNames>(name: Name,resultHandler: ResultHandler): this {if(this.isNameAllowed(name)){this.#storage.set(name,Callback.defineCallback(resultHandler));}returnthis;}

Generic type variables:

NameDescription
Name extends AllowNamesA 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: typeDescription
name: NameA 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: ResultHandlerThe function of ResultHandler to handle the result of the ResultCallbackfunction before its result returns

Returns:

ReturnsTypeDescription
thisobjectThe 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`. */constcallback=newCallback('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.

publicsetErrorCallback<NameextendsAllowNames>(name: Name,message: string|ErrorMessage,throwOnState: boolean=false): this {this.setCallback(name,Callback.defineErrorCallback(message,throwOnState));returnthis;}

Generic type variables:

NameDescription
Name extends AllowNamesA 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: typeDescription
name: NameA 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 | ErrorMessageThe message of string type or ErrorMessage interface, to throw with an error of ValidationError
throwOnState: booleanA state of boolean type on which an error of ValidationError should be thrown. By default, it's set to false

Returns:

ReturnsTypeDescription
thisobjectThe 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`. */constcallback=newCallback('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:

MethodDescription
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:

ConstructorDescription
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.

publicgetcomponent(): ComponentRef<DynamicComponent>|undefined{returnthis.#component;}

ComponentLoader.prototype.created

Returns the creation state of a dynamic component.

publicgetcreated(): boolean {returnthis.$created;}

ComponentLoader.prototype.instance

Returns an instance of the created dynamic component.

publicgetinstance(): DynamicComponent|undefined{returnthis.#component?.instance;}

ComponentLoader static methods


ComponentLoader.isContainer()

Checks if the provided value is a ViewContainerRef type.

staticisContainer(value: any,callback?: ResultCallback): valueisViewContainerRef{returnis.objectKey(value,'_hostLView',callback);}

Parameters:

Name: typeDescription
value: anyThe value of any type to check
callback?: ResultCallbackAn optional ResultCallback function to handle the result of the check

Returns:

ReturnsTypeDescription
value is ViewContainerRefbooleanThe 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>',})exportclassExampleComponentimplementsAfterViewInit{
@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.

staticisFactoryResolver(value: any,callback?: ResultCallback): valueisComponentFactoryResolver{returnis.objectKeyIn(value,'resolveComponentFactory',callback);}

Parameters:

Name: typeDescription
value: anyThe value of any type to check
callback?: ResultCallbackAn optional ResultCallback function to handle the result of the check

Returns:

ReturnsTypeDescription
value is ComponentFactoryResolverbooleanThe 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: ''})exportclassExampleComponent{constructor(factoryResolver: ComponentFactoryResolver){ComponentLoader.isFactoryResolver(factoryResolver);}}

ComponentLoader constructor


Creates an instance with initializing ComponentFactoryResolver.

constructor(protectedfactoryResolver: 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: typeDescription
factoryResolver: ComponentFactoryResolverThe 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: ''})exportclassExampleComponentextendsComponentLoader{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

publicassignProperties<Objextendsobject,KeyextendskeyofDynamicComponent>(object: Obj, ...keys: Key[]): this {if(guard.object(object)&&guard.array(keys)&&keys.length>0){
keys.forEach((key)=>{Object.assign(this.instance,{[key]: object[keyasstringaskeyofObj],});});}else{
Object.assign(this.instance,object);}returnthis;}

Generic type variables:

NameDescription
Obj extends objectA 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 DynamicComponentA 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: typeDescription
object: ObjAn 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`})exportclassDynamicComponent{firstName='';}
@Component({template: '<div #newContainer></div>',})exportclassExampleComponentextendsComponentLoader<DynamicComponent>implementsAfterViewInit{
@ViewChild('newContainer',{read: ViewContainerRef})container: any;constructor(publicfactoryResolver: 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.

publiccreateComponent(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));}elseif(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);}}returnthis;}

Parameters:

Name: typeDescription
component?: Type<DynamicComponent>An optional class of a DynamicComponent type
container: ViewContainerRefA container of ViewContainerRef type to load component host view to it
callback?: ResultCallbackAn 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`})exportclassDynamicComponent{}
@Component({template: '<div #newContainer></div>',})exportclassExampleComponentextendsComponentLoader<DynamicComponent>implementsAfterViewInit{
@ViewChild('newContainer',{read: ViewContainerRef})container: any;constructor(publicfactoryResolver: 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.

publicdestroyComponent(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`.returnthis.#component;}

Parameters:

Name: typeDescription
callback?: ResultCallbackAn 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`})exportclassDynamicComponent{}
@Component({template: '<div #newContainer></div>',})exportclassExampleComponentextendsComponentLoader<DynamicComponent>implementsAfterViewInit{
@ViewChild('newContainer',{read: ViewContainerRef})container: any;constructor(publicfactoryResolver: 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.

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

Generic type variables:

NameDescription
Key extends keyof DynamicComponentA 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: typeDescription
key: KeyThe 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: ResultCallbackThe 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`})exportclassDynamicComponent{firstName='My first name';}
@Component({template: '<div #newContainer></div>',})exportclassExampleComponentextendsComponentLoader<DynamicComponent>implementsAfterViewInit{
@ViewChild('newContainer',{read: ViewContainerRef})container: any;constructor(publicfactoryResolver: 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.

publicisCreated(callback?: ResultCallback): boolean {returnis.object(this.#component,callback);}

Parameters:

Name: typeDescription
callback?: ResultCallbackAn 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`})exportclassDynamicComponent{}
@Component({template: '<div #newContainer></div>',})exportclassExampleComponentextendsComponentLoader<DynamicComponent>implementsAfterViewInit{
@ViewChild('newContainer',{read: ViewContainerRef})container: any;constructor(publicfactoryResolver: 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.

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

Parameters:

Name: typeDescription
container: ViewContainerRefThe value of a class type to retrieve the factory object
callback: ResultCallbackAn 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`})exportclassDynamicComponent{}
@Component({template: '<div #newContainer></div>',})exportclassExampleComponentextendsComponentLoader<DynamicComponent>implementsAfterViewInit{
@ViewChild('newContainer',{read: ViewContainerRef})container: any;constructor(publicfactoryResolver: 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.

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

Parameters:

Name: typeDescription
component: Type<DynamicComponent>Class of a DynamicComponent type to retrieve the factory object
callback: ResultCallbackAn 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`})exportclassDynamicComponent{}
@Component({template: '<div #newContainer></div>',})exportclassExampleComponentextendsComponentLoader<DynamicComponent>implementsAfterViewInit{
@ViewChild('newContainer',{read: ViewContainerRef})container: any;constructor(publicfactoryResolver: 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.

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

Generic type variables:

NameDescription
Key extends keyof DynamicComponentA 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: typeDescription
key: KeyThe 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: ResultCallbackThe 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`})exportclassDynamicComponent{firstName='';}
@Component({template: '<div #newContainer></div>',})exportclassExampleComponentextendsComponentLoader<DynamicComponent>implementsAfterViewInit{
@ViewChild('newContainer',{read: ViewContainerRef})container: any;constructor(publicfactoryResolver: 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:

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

Constructor:

ConstructorDescription
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].

statictemplate=`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.

publicfix='';

ValidationError.prototype.name

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

publicname=ValidationError.name;

ValidationError.prototype.problem

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

publicproblem='';

ValidationError static methods


ValidationError.defineMessage()

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

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

Parameters:

Name: typeDescription
message: ErrorMessageAn 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';constfix='There is no solution to the described problem.';constproblem='The problem has no solution.';/** * Returns * -------- * Problem: The problem has no solution. => Fix: There is no solution to the described problem. */consterrorMessage=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.

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

Parameters:

Name: typeDescription
message: string | ErrorMessageThe 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';constfix='There is no solution to the described problem.';constproblem='The problem has no solution.';constvalidationError=newValidationError({ fix, problem });

Interface

ErrorMessage

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

interfaceErrorMessage{/** * 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 ResultCallbackfunction before its result returns.

typeResultHandler=(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.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages