Question
Dynamically loading and rendering External files as component in angular
I have a use-case, where I should render an external angular component or web-component in an angular application.
I have created a sample application (stackblitz) to reproduce the scenario and below is the visual expecation.
In the sample code, to compile a angular component I use
<div style="margin:20px; display: flex; max-height: 500px;">
<div style="max-width:250px; overflow-y: scroll;">
<button (click)="onInternalControl()">Internal Component</button>
<ng-template #internalTemplate>this is internal template</ng-template>
</div>
<div style="width:250px; height: 150px; overflow-y: scroll;">
<button (click)="onExternalControl()">External Component</button>
<ng-template #externalTemplate>this is external template</ng-template>
</div>
</div>
The below is the component code
export class AppComponent implements OnInit {
@ViewChild('internalTemplate', { read: ViewContainerRef })
internalTemplate: any;
@ViewChild('externalTemplate', { read: ViewContainerRef })
externalTemplate: any;
constructor() {}
ngOnInit() {}
onInternalControl() {
this.internalTemplate.clear();
this.internalTemplate.createComponent(LabelComponent);
}
onExternalControl() {
this.externalTemplate.clear();
// how to dynamically register and load web-component in the ng-template (externalTemplate)
// e.g., assets/external-label.js
}
}
The below code is the web component which is exepected to be render on click of EXTERNAL_COMPONENT button.
class ExternalLabel extends HTMLElement {
// The browser calls this method when the element is
// added to the DOM.
connectedCallback() {
let $p = document.createElement('p');
$p.style.backgroundColor = 'red';
$p.style.width = '250px';
$p.style.height = '250px';
$p.innerHTML = 'External Label Control';
this._shadowRoot.appendChild($p);
}
}
// Register the ExternalLabel component using the tag name <ext-label>.
customElements.define('ext-label', ExternalLabel);
How can I dynamically register and load the external label web component?