How to pass complex values to Angular Elements in React

Share on facebook
Share on google
Share on twitter
Share on linkedin

A common problem when using Angular Elements with other frameworks such as React is that all inputs will be stringified. That means if you pass an object using attributes, you will get "[object, Object]"  which is not something we can work with, in our Angular Elements components.

 

This post will show, how to pass complex values (object, arrays, numbers, and booleans) to Angular Elements in React.

Attributes and properties

To understand the solution, we first need to make sure we know the difference between an attribute and a property.

Attribute

An attribute is a value we assign to DOM elements.

Example:

<app-crud-item key={i} is-read-only={true}></app-crud-item>

Here is-read-only is the attribute and this is being mapped to the property isReadOnly because of how Angular Elements map attributes to properties.

Property

A property is a Javascript property/field/value on the DOM object when accessing the DOM element in Javascript.

Passing complex values to Angular elements in React

Consider, that we have a React todo app, that wants to use a CrudItemComponent; An Angular Elements component for creating a list item with CRUD controls (delete and update buttons).

We want to render this Angular CRUD component:

And we export this as part of an Angular Elements UI lib module:

In a react app, we pass complex values by setting the properties using plain JS in the useEffect hook:

And voila, that is how we pass complex values to an Angular Elements bundle from other frameworks such as React.

Do you want to become an Angular architect? Check out Angular Architect Accelerator.

Related Posts and Comments

single-spa walkthrough from scratch

In this video, I will be doing a walkthrough from scratch on how to create a micro frontend application using single-spa having both React and AngularJS running together in one application. Do you want to become an Angular architect? Check out Angular Architect Accelerator.

Read More »

Angular vs React – When to use what

Ohoy, religious grounds ahead! I have been working with both Angular and React applications and have been working for companies that have switched between using Angular or React. From outside, the two frameworks can look like substitutes as they are both single page application framework, but in fact, they are quite different and the switching

Read More »