Skip to content

Instantly share code, notes, and snippets.

@mfp22
Created March 6, 2020 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfp22/5f9717ff297deb69125afab8480eb65e to your computer and use it in GitHub Desktop.
Save mfp22/5f9717ff297deb69125afab8480eb65e to your computer and use it in GitHub Desktop.
import { SimpleChanges } from '@angular/core';
export function AsyncInput(inputName?: string) {
return (target, rxInputName: string) => {
inputName = inputName || rxInputName.slice(0, -1); // Remove '$' ('data$' => 'data')
const oldOnChanges = target.ngOnChanges;
const oldOnDestroy = target.ngOnDestroy;
target.ngOnChanges = function(changes: SimpleChanges) {
const inputChange = changes[inputName];
if (inputChange) {
const useDefault =
inputChange.isFirstChange && inputChange.currentValue === undefined;
if (!useDefault) {
this[rxInputName].next(changes[inputName].currentValue);
}
}
if (oldOnChanges) {
oldOnChanges.bind(this)(changes);
}
};
target.ngOnDestroy = function() {
this[rxInputName].next();
this[rxInputName].complete();
if (oldOnDestroy) {
oldOnDestroy.bind(this)();
}
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment