Skip to content

Instantly share code, notes, and snippets.

@dimfeld
Created April 30, 2020 19:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dimfeld/880decfe300f88119bb4f1141a66e527 to your computer and use it in GitHub Desktop.
Save dimfeld/880decfe300f88119bb4f1141a66e527 to your computer and use it in GitHub Desktop.
export default function (
Component: typeof SvelteComponent,
events?: { [svelteEvent: string]: string }
) {
return class {
$element: Element[];
initialProps: { [key: string]: any };
component: SvelteComponent;
constructor($element) {
'ngInject';
this.$element = $element;
}
addInitialProps(extraProps) {
this.initialProps = {
...this.initialProps,
...extraProps,
};
}
$postLink() {
this.component = new Component({
target: this.$element[0],
props: this.initialProps,
});
each(events || {}, (angularBinding, svelteEvent) => {
this.component.$on(svelteEvent, ({ detail }) => {
this[angularBinding](detail);
});
});
}
$onChanges(changes) {
let changed = {};
each(changes, ({ currentValue }, key) => {
changed[key] = currentValue;
});
if (this.component) {
this.component.$set(changed);
} else {
this.initialProps = {
...this.initialProps,
...changed,
};
}
}
$onDestroy() {
if (this.component) {
this.component.$destroy();
}
}
};
}
@dimfeld
Copy link
Author

dimfeld commented Jun 10, 2020

If you're not using Typescript, you can find a plain ES6 version of this Gist at https://gist.github.com/rcline/af3a58cd5324dfcd5e7e22e7f3c64347

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment