Created
March 19, 2020 08:49
-
-
Save akoppela/fdf22dc2dcd638d02b0873a0c2afaf17 to your computer and use it in GitHub Desktop.
Bare minimum to compile AngularJS component with custom Element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular | |
.module('shared', []) | |
.run(function ($rootScope, $compile) { | |
'use strict'; | |
function CustomElementConstructor() { | |
// Super call | |
var self = HTMLElement.call(this) || this; | |
// Create custom element scope which is used as a store of data and as a parent for component scope. | |
self.$scope = $rootScope.$new(); | |
return self; | |
} | |
CustomElementConstructor.prototype = Object.create(HTMLElement.prototype, { | |
constructor: { | |
value: CustomElementConstructor, | |
}, | |
connectedCallback: { | |
value: function () { | |
// Create component scope which is used only while the custom element is in DOM. | |
this.componentScope = this.$scope.$new(); | |
// Create a component element. It should be an AngularJS component/directive. | |
this.componentElement = angular.element('<my-own-component></my-own-component>'); | |
// Append and compile. | |
angular.element(this).append(this.componentElement); | |
$compile(this.componentElement)(this.componentScope); | |
}, | |
}, | |
disconnectedCallback: { | |
value: function () { | |
// Remove the component scope and element when custom element is removed from the DOM. | |
// The component scope and element is created each time custom element is added to the DOM. | |
this.componentScope.$destroy(); | |
this.componentElement.remove(); | |
}, | |
}, | |
}); | |
window.customElements.define('my-own-custom-element-wrapper-for-angular-component', CustomElementConstructor); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment