My issue can be summed up as follows:
I am interested in dynamically loading external Angular
components from a remote server at runtime
. I have successfully achieved this with the help of a blog post by Manfred Steyer
However, my specific challenge lies in passing a data
object to the component being loaded at runtime
. While Manfred Steyer demonstrates how to achieve this, it does not cover dealing with objects.
To elaborate on my process:
Firstly, I create a separate Angular
project that accepts a data object like so:
Within RandomComponent.ts
:
Interface Random: {
name: string;
age: number;
}[]
@Input() data: Random;
Inside RandomComponent.html
:
<div>
<div *ngFor="let d of data">{{d.name}}</div>
</div>
Next, I build this component and receive a file named: random-component.bundle.js
. This file is then hosted on a server and rendered when required.
Now, within the main Angular project, I aim to load this file and provide it with a data object. Following the guidance from Manfred Steyer, the code would look something like this:
// creating element from bundle
const script = document.createElement('script');
script.src = 'assets/random-component.bundle.js';
document.body.appendChild(script);
// creating new element based on selector from bundle
const data = [{name: 'Dave', age: 19}, {name: 'Charly', age: 23}];
const component = document.createElement('random-component');
component.setAttribute('data', data);
However, I am encountering difficulties in setting an attribute in this manner. Any suggestions?