Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows.

export class Config {
  constructor(public index: number, public junk: string[] = []) { }
  public count() : number { return this.junk.length; }
}

After declaring it, I pass it into the input decorated field of my components like this (@Input() config : Config;).

<div *ngFor="let thing of stuff; let config={index:index,junk:junk};">
  <app-thingy [data]="thing"
              [config]="config">
  </app-thingy>
</div>

Even though I can access this.config in ngOnChanges() and see the values that I've set, the method is not accessible. Additionally, any additional parameters in the constructor or public fields in the class are not recognized either. Only the explicitly assigned HTML markup fields are available.

ngOnChanges(changes: SimpleChanges): void {
  if (changes.config) {
    //console.log((new Config()).count());
    console.log((this.config.count()));
  }
}

An error occurs when trying to call the method on the object directly. However, casting it using this.config as Config leads to the same result.

It seems that the object passed from the HTML markup may not be typed as Config, hence lacking any methods/variables not explicitly assigned. Is there a way to make the computer recognize the class and its convenience methods without resorting to hacky solutions?

The potential solution I envision involves constructing an internal Config object by copying the fields from the passed-in object and binding the HTML interpolators to that instead. However, this approach feels somewhat clumsy and possibly flawed...

Answer №1

It is unclear what the intention is behind using

let config={index:index,junk:junk};
in your code, as it seems to result in an error when tested. However, by removing this line and properly defining a new Config in the parent component, the code should function correctly.

Parent Component:

config = new Config(1,['one','two'])

Parent's HTML:

<div *ngFor="let thing of stuff">
  <app-thingy [data]="thing" [config]="config"></app-thingy>
</div>

Child Component:

ngOnChanges(changes: SimpleChanges): void {
  if (changes.config) {
    console.log((this.config.count()));
  }
}

Everything appears to be working smoothly now! See the DEMO here: https://stackblitz.com/edit/angular-fnmk41?file=app%2Fapp.component.ts

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

Transparent background with opaque text

I noticed that my div has a gray background with some opacity. <div className="absolute w-full h-full top-0 left-0 right-0 bottom-0 bg-slate-500 opacity-50 z-10"> <p className="relative top-1/2 px-8 text-center hea ...

Unable to get angular button hold loop to work properly

My goal is to create a button that can be pressed once to execute a single command, but also has the capability to hold the button down and execute the command multiple times while still holding it. I am working with AngularJs (though I don't believe ...

What is the best way to define a model class within my Angular 2 component using TypeScript?

As I delve into Angular 2 and TypeScript, I am keen on adopting best practices. I have decided to move away from a simple JavaScript model ({ }) in favor of creating a TypeScript class. However, it seems that Angular 2 is not very fond of my approach. T ...

Angular - A Guide to Managing User Roles by Toggling Checkbox Values

In my current project, I am developing a web portal using Angular-7 for the frontend and Laravel-5.8 for the backend. Additionally, I am utilizing Laravel Spatie for User Role Management. Within the user.component.ts file: export class UsersComponent imp ...

Toggle the checkbox to update the count

I am trying to implement a feature where the user can check a maximum of 4 checkboxes. I have managed to achieve this functionality in the code below. When the user unchecks a box, the count should decrease by one and they should be able to check another c ...

Display and conceal table columns dynamically in Vue by utilizing the Vuetify data table functionality

Looking for an example: How to show hide columns of vuetify data table using v-select list I have created something similar, but I'm facing an issue where the table doesn't refresh when changing the header data: https://codepen.io/Meff1/pen/vY ...

Is there a way to obtain the full class name if only a portion of it is known?

I am trying to extract the complete classname of an element, but I only have partial information about it. <div class="anotherclass my-class-no-1 onemoreclass...">div> Currently, I can select the element using this: $([class*="my-class-no-"]... ...

Is there a way to locate child components without needing to designate the higher-order component encompassing them?

When working with Material-ui, I often find that its extensible nature can be a hindrance when it comes to testing. For example, even if I am using the following code: const MyEventButton = () => (<IconButton /> <Event /> </IconButton ...

Ways to include text with specific choices in a drop-down menu?

Within a form, I am encountering a situation where a select box's options are pre-selected through ajax based on a previously entered value. I am now seeking a way to append additional text to these pre-selected options only. for (i in data) { $("#my ...

Saving JSON data in a variable or array post subscription: What's the preferred method?

I have been receiving JSON files in the following format: {streetAddress: "Kosterlijand 20", postalCode: "3980", city: "Bunnik", country: "Netherlands"} Although the length of these files varies, the structure always remains the same: {key: "string valu ...

The total height of an HTML element, which takes into account the margin of the element itself

Is there a way to accurately calculate the height of an element including margins, even when dealing with child elements that have larger margins than their parents? HTMLElement.offsetHeight provides the height excluding margin, while this function from ...

Issue: mongoose.model is not a valid function

I've been diving into several MEAN tutorials, and I've hit a snag that none of them seem to address. I keep encountering this error message: Uncaught TypeError: mongoose.model is not a function Even after removing node_modules and reinstalling ...

Adjusting iframe height based on its source URL using JQuery

Currently, I have implemented a script to adjust the height of YouTube iframes in order to maintain a 16:9 aspect ratio while keeping the width at 100% of the container. The challenge I am facing is ensuring that the script only affects YouTube videos and ...

Having difficulty transferring types to and from a custom module?

I'm currently faced with an issue while working on a typescript module within a larger monorepo. I am having difficulty importing types from one package into another via node modules. The types are located at ./types, and my package.json contains a ke ...

Guide to dynamically using array.map based on a condition in React

I am encountering an issue with a modal screen that contains two dropdowns and a text input field. The problem arises when the second dropdown is set to “is empty”, as the text input field should then disappear, leaving just the two dropdown inputs on ...

Create an interactive JSON tree structure

I am looking to create a JSON tree from an array. My array is structured like this: var arraySource = []; arraySource.push({key : "fr", value: "france"}); arraySource.push({key : "es", value: "spain"}); //... console.debug(arraySource); The desired JSON ...

How can I simply show a specific value from an object in Vue?

I've created a Vue application that filters messages and displays them on a page. Currently, when a user selects a message from the list, the entire JSON data associated with that message is shown on the page. However, I want to only display a specifi ...

Navigating from the root view to a (grand)child view with Angular2: Mastering Direct Links

I am currently exploring Angular 2 and have encountered a perplexing issue that I need assistance in debugging. An Illustrative Scenario In my project, I have an AppComponent that manages the fundamental level routing. Each subsequent level of routing is ...

Arranging the data in my JSON reply

{ "JsonResult": { "List": [{ "Subject": "Something", "Type": 0, "TypeDescription": "Referral" }], } } When I hit my service, I receive a sample JSON response. After that, there is a button with ...

Is it possible to find a more efficient approach than calling setState just once within useEffect?

In my react application, I find myself using this particular pattern frequently: export default function Profile() { const [username, setUsername] = React.useState<string | null>(null); React.useEffect(()=>{ fetch(`/api/userprofil ...