NgMix
Angular schematic library for generating TypeScript mixins designed for Angular Components.
TypeScript mixins are then used to implement a composition pattern to share common logic across Angular components.
Table of Contents
Requirements
Installation
Install via npm:
npm i ng-mix
Usage
CLI Command
Mixin Overview
-
The following code will be generated (sample.mixin.ts)
import { Injectable, OnInit } from '@angular/core';
import { BaseInjectorConstructor } from 'ng-mix';
export const SampleMixin = <Tbase extends BaseInjectorConstructor>(superClass: Tbase) => {
@Injectable()
class Sample extends superClass implements OnInit {
ngOnInit(): void {
super.ngOnInit();
}
}
return Sample;
}
-
All mixins will inherit BaseClassInjector
Back to top
Usage with Component
- Extend your component class with the mixin.
import { Component, Injector } from '@angular/core';
import { SampleMixin } from './sample.mixin';
import { Base } from 'ng-mix';
@Component({
selector: 'app-component',
templateUrl: './app-component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent extends SampleMixin(Base) {
constructor(public injector: Injector) {
super(injector);
}
}
- Provide ng-mix's Base class to the mixin.
- Provide the injector to the mixin(s) by passing it into the super call in the constructor.
Back to top
Composing with Mixins
Back to top
Angular Lifecycle Hooks
-
When implementing an Angular lifecycle hook method on a mixin or component using mixin(s), always call super.[ lifecycle method] when mixins are used to ensure the lifecycle methods for all mixins are invoked.
export const SampleMixin = <Tbase extends BaseInjectorConstructor>(superClass: Tbase) => {
@Injectable()
class Sample extends superClass {
...
ngOnInit(): void {
super.ngOnInit();
}
...
}
return Sample;
}
@Component({
...
})
export class AppComponent extends SampleMixin(Base) {
...
ngOnInit(): void {
super.ngOnInit();
}
...
}
Back to top
Angular @Input and @Outputs Decorators
-
If @Input/@Output decorators are used in mixins, they will need to be declared in the @Component decorator of the component.
export const SampleMixin = <Tbase extends BaseInjectorConstructor>(superClass: Tbase) => {
@Injectable()
class Sample extends superClass {
@Input sampleInput = '';
@Output sampleOutput = new EventEmitter<any>();
...
}
return Sample;
}
@Component({
...
inputs: ['sampleInput'],
outputs: ['sampleOutput']
})
export class AppComponent extends SampleMixin(Base) { ... }
Back to top
Angular Services