angular Struggling with @Input and data interpolation functionality within web components

I have built a collection of web components designed for various Angular projects. To make these components reusable, I am using @angular/elements to convert them into custom elements and then serving them via http-server.

One of the components I developed is a custom h1 element:

h1-component.ts

import { Component, Input, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-h1',
  templateUrl: './h1.component.html',
  styleUrls: ['./h1.component.scss'],
  encapsulation: ViewEncapsulation.ShadowDom
})

export class H1Component {
  private _text: string = '';

  @Input() set text(text: string) { this._text = text; }
  get text(): string { return this._text; }
}

h1-component.html

<h1>{{ text }}</h1>

In my app.module.ts, I have declared my custom element as

const h1El = createCustomElement(H1Component, {
  injector: this.injector
});
customElements.define('custom-h1', h1El);

The setup of my application follows the guidelines outlined in https://angular.io/guide/elements

After completing all my components, I moved on to testing them by incorporating them into another Angular application and configuring the environment to load my script. However, I encountered an issue where my custom components were not displaying the @Input values properly.

In my new application:

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  header = "Custom header";
}

app.component.html

<custom-h1 text="{{ header }}"></custom-h1>

Upon running ng serve on my new application and setting up http-server for my library of components, I expected to see "Custom header" displayed. However, there was no output visible.

If I manually input a string value into text (e.g.,

<custom-h1 text="Custom header string"></custom-h1>
), then I can see the correct output of "Custom header string."

Any insights or recommendations? References would be greatly appreciated. Thank you.

Answer №1

Here is a possible solution to the issue: https://github.com/angular/angular/issues/29050. When using custom elements, the order in which lifecycle hooks execute may change. This can lead to variables being undefined in ngOnInit() but not in ngOnChanges(). I am currently experimenting with ways to ensure that ngOnChanges() runs before ngOnInit(), but have not found a successful method yet.

To address this, you can try:

ngOnChanges(): void {
    this._text = text;
}

You may also find this discussion helpful: Angular Elements: @Input decorator not working with variables

Answer №2

perhaps this could be beneficial

<custom-h1 [text]="header"></custom-h1>

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

What is the most efficient way to minimize the use of if statements in an Angular component when calling a specific function?

Currently, I am working on an Angular 7 temperature conversion application. Within my formGroup, there are inputs and outputs along with two multi-select dropdowns where users can choose the unit of temperature 'From' and 'To' for conve ...

Launching an Angular application from the local server

I have successfully deployed an Angular frontend on a server. It is functioning well, with three scripts: /runtime.0fad6a04e0afb2fa.js /polyfills.24f3ec2108a8e0ab.js /main.a9b28b9970fe807a.js My goal is to start this application in Firefox without ...

Error in zone: 140 - Property 'remove' is not readable

I'm brand new to kendo ui. I successfully set up a prototype in my fiddle with a working delete confirmation window. However, when I try to integrate it into my existing codebase, I encounter an error: Cannot read property 'remove' at the li ...

Leveraging TypeScript alongside body-parser to access properties within req.body

I'm currently developing a web application using TypeScript and integrating the body-parser middleware to handle JSON request bodies. I've encountered type errors while attempting to access properties on the Request.body object. For instance, wh ...

Attempting to successfully upload this Angular 7 form to my TypeScript code. Making use of ngForm and [(ngModel)] to achieve this

I am having trouble passing form information using the onSubmit() function. It seems to be undefined when I try to execute it initially. Could there be a syntax error that I'm missing? <form class="gf-formbox" name="credentials" (ngSubmit)="onSubm ...

What steps can be taken to effectively build a test suite architecture using Jest?

After exploring all the available resources on the Jest documentation website, including various guides and examples, I have yet to find a solution to my specific question. I am in search of a methodology that would enable me to individually run test case ...

Develop a TypeScript class that includes only a single calculated attribute

Is it advisable to create a class solely for one computed property as a key in order to manage the JSON response? I am faced with an issue where I need to create a blog post. There are 3 variations to choose from: A) Blog Post EN B) Blog Post GER C) Bl ...

Exploring the world of interfaces in nested mapping functions

Currently, I'm faced with the challenge of mapping an array inside another map with an array. These are the specific interfaces that I am working with: interface Props { columns: Array<{field: string, headerName: string, width: number}>; row ...

Unraveling the mysteries of webpack configuration

import * as webpack from 'webpack'; ... transforms.webpackConfiguration = (config: webpack.Configuration) => { patchWebpackConfig(config, options); While reviewing code within an Angular project, I came across the snippet above. One part ...

The state data is not being properly updated and is getting duplicated

While developing a loop to parse my API data, I encountered an issue where the values obtained were not being captured properly for dynamically loading corresponding components based on their characteristics. The problem arose after implementing useState() ...

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...

Tips for generating a JSON-driven table in Angular 2

I'm attempting to build a dynamic datagrid in angular2 using a JSON object as the source. The challenge I face is not knowing the structure of the columns within the table, making it difficult to render the rows properly. My understanding is that I n ...

"Exploring the depths of Webpack's module

This is my first venture into creating an Angular 2 application within MVC Core, utilizing TypeScript 2.2, Angular2, and Webpack. I have been closely following the Angular Documentation, but despite referencing the latest NPM Modules, I encounter errors w ...

Limitations of MaterialUI Slider

Looking for a solution to distribute 350 points across 8 sliders, each with a range of 0-100 and 5 marks at 0, 25, 50, 75, and 100. With each step consuming or returning 25 points, the challenge lies in allowing users to adjust the points allocation withou ...

Angular - HighChart TreeMap does not refresh with updated data

I've been working on updating my highcharts treemap with fresh data, but for some reason, it doesn't seem to reflect the changes when I click on update. The only thing that seems to change is the title. I've tried the suggested solution on ...

Utilizing Async and await for transferring data between components

I currently have 2 components and 1 service file. The **Component** is where I need the response to be displayed. My goal is to call a function from the Master component in Component 1 and receive the response back in the Master component. My concern lies ...

Is it possible that Typescript does not use type-guard to check for undefined when verifying the truthiness of a variable?

class Base {} function log(arg: number) { console.log(arg); } function fn<T extends typeof Base>( instance: Partial<InstanceType<T>>, key: keyof InstanceType<T>, ) { const val = instance[key]; if (val) { ...

Angular 4: Retrieving the selected element's object from a collection of elements

In my x.component.html file, I have a list of objects that are being displayed in Bootstrap cards like this: <div *ngFor="let item of items | async"> <div class="row"> <div class="col-lg-6"> <div class="card ...

Enhanced Autocomplete Feature with Select All Option in MUI

Currently, I am utilizing Material UI (5) and the Autocomplete component with the option for multiselect enabled. In addition, I am implementing the "checkbox" customization as per the MUI documentation. To enhance this further, I am attempting to incorpor ...

What could be causing the error message "why can't shows read property

Within my Ionic-Angular application, I have successfully loaded the content from the database and printed it on the console. However, I am facing an issue where I cannot bind this content to the view. The error message that appears is displayed in https:// ...