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.

Hi there!

I’m Christian, a freelance software developer helping people with Angular development. If you like my posts, make sure to follow me on Twitter.

Related Posts and Comments