Assign a value to an array property of a separate Angular component

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?

Answer №1

Verify the @Input identifier in the random-component module. Be sure that the attribute name matches a valid property within the component.

Answer №2

If you're curious about this method!

Instead of simply passing an array, I opt to pass a stringified version of the array using JSON.stringify(data). This converts the array into a string which can then be passed as an attribute:

Main ingredient

  const component = document.createElement(identifier);
  component.setAttribute('data', JSON.stringify(data));
  const content = document.getElementById('content');
  content.appendChild(component);

External Equipment - random.component.ts

  parseData(data: string) {
    return JSON.parse(data);
  }

External Equipment - random.component.html

<div>
    <div *ngFor="let d of parseData(data)">{{d.name}}</div>
</div>

It does the job! However, there are some drawbacks with the one-way binding

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a new project using Firebase Functions along with a Node.js backend and a React.js frontend

In the process of developing my application, I have chosen to utilize node.js, express.js, and Firebase with firebase functions, all coded in TypeScript. For the client side framework, I am interested in incorporating react.js. Currently, I have set up nod ...

Issue "unable to use property "useEffect", dispatcher is undefined" arises exclusively when working with a local npm package

I am currently in the process of creating my very own private npm package to streamline some components and functions that I frequently use across various React TypeScript projects. However, when I try to install the package locally using its local path, ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

The unique behavior of nested observables within an Ionic2/Angular2 application

Creating an ionic login module involves using 2 observables, with one nested inside the other. Uncertainty exists regarding whether this is the correct implementation. The process includes calling the getHTTP() method to retrieve a string. If the string i ...

What are some effective strategies for resolving the persistent issue of Visual Studio Code warnings, MDN Reference difficulties, and other challenges?

Is there a way to turn off TypeScript warnings and completely disable TS in Visual Studio Code for standard JavaScript files while using SvelteKit? I typically opt out of using TS when starting a new project. Furthermore, is it possible to get rid of the ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

Error TS2322: The specified type Login cannot be assigned to the given type

I've been facing an issue while working on my app in react native. The error message I keep encountering is as follows: TS2322: Type 'typeof Login' is not assignable to type ScreenComponentType<ParamListBase, "Login"> | undefined Type ...

Translating Bootstrap 5 into Angular components for version 13 and above

In Angular, the lack of support for optional host-elements and containerless components means that each component comes with its own div wrapper. However, when designing Bootstrap components, a host-less component (without an extra div) is needed to mainta ...

Encountered an issue during installation: Error message states that Typings command was not

I've encountered permission errors with npm, so I decided to reinstall it. However, I'm facing an issue with the 'typings' part where it displays a 'typings: command not found' error. This problem seems to be related to Angula ...

The specified function is not recognized within the HTMLButtonElement's onclick event in Angular 4

Recently diving into Angular and facing a perplexing issue: "openClose is not defined at HTMLButtonElement.onclick (index:13)" Even after scouring through various resources, the error seems to be rooted in the index page rather than within any of the app ...

How can you load an HTML page in Puppeteer without any CSS, JS, fonts, or images?

My current task involves using Puppeteer to scrape data from multiple pages in a short amount of time. However, upon closer inspection, I realized that the process is not as efficient as I would like it to be. This is because I am only interested in spec ...

Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes? Thank you. <div class="col-2" *ngFor="let movie of moviesList"> <div class="movie"> {{ movie.attributes.title }} ...

Storing the data object in an array using Angular and Mongoose in Node.js

I've encountered an issue with my Angular form connected to Node JS and MongoDB. While some data from the form gets saved in mongoDB, there are certain fields like measurementUsed and testTolerance that do not get saved properly. This is how my model ...

The function this.gridApi.refreshInfiniteCache() is failing to remove the selectedRows from the grid

While utilizing the Infinite Row Model, I encountered an issue where deleting a selected row from the Grid and then refreshing the cache resulted in unexpected behavior. For example, if I delete a row with id = 1 and then call refreshInfiniteCache(), a n ...

Accessing JSON object from a URL via a web API using Angular 2 and TypeScript

`Hello, I am in need of some assistance in retrieving JSON data from a web API using Visual Studio 2015 .net Core, Angular 2 & Typescript. The Angular2 folders are located in /wwwroot/libs. Currently, I am utilizing Angular 2's http.get() method. Ho ...

Angular: Converting JSON responses from HttpClient requests into class instances

I am facing an issue with the following code: public fetchResults(searchTerm: string): Observable<Array<SearchResult>> { let params = new HttpParams().set('searchTerm', searchTerm); return this.http .get<Array< ...

Double-tap bug with Image Picker in Typescript React Native (non-expo)

Well, here’s the situation - some good news and some bad news. First, the good news is that the code below is functioning smoothly. Now, the not-so-good news is that I find myself having to select the image twice before it actually shows up on the clie ...

Using TypeScript to structure and organize data in order to reduce the amount of overly complex code blocks

Within my TypeScript module, I have multiple array structures each intended to store distinct data sets. var monthlySheetP = [ ['Year', 'Month', 'Program', 'Region', 'Market', 'Country', &apo ...

I need to connect data to a textarea element within an ASP.NET MVC view

<div class="col-md-6"> <label>Share Your Business, Accomplishments & Dreams (500 Words Maximum)</label> <textarea name="Description" type="text" placeholder="SHARE YOUR BUSINESS, ACCOMPLIS ...

A recent update to ngx-mask v16.2.6 has caused an issue where the module "ngx-mask" is unable to export the member "NgxMaskModule."

Following my upgrade to ngx-mask version 16.2.6, I have encountered an issue where the Angular compiler is unable to locate NgxMaskModule exported from 'ngx-mask'. The error message that I'm seeing reads as follows: ERROR in ./src/.....ts:2 ...