Engage with the item provided to an Angular2 component as an Input parameter

In a nutshell, the issue stems from a missing 'this' when referencing the @Input'ed variables.

Currently, I have a parent class that will eventually showcase a list of "QuestionComponents".

The pertinent section of the parent class template is shown below:

<question [(justText)]="testText"  [(justObj)]="testObj" [(myQuestion)]="singleQuestion"></question>

Essentially, I retrieve the "singleQuestion" object from an HTTP service call. The Question class, from which "singleQuestion" originates, features a basic "toString" method for streamlined output debugging.

testText, textObj, and singleQuestion are progressively complex objects as I conduct tests. Currently, there's only one "question" as I build my comprehension.

The child "QuestionComponent" has the following structure:

@Component ({
    selector:
        'question',
    templateUrl:
        './app/components/question/question.component.html',
    directives: [FORM_DIRECTIVES],

})


export class QuestionComponent {

    @Input() myQuestion:USGSQuestion
    @Input() justText:string
    @Input() justObj:object

     constructor() {

    }

    onClick() {
        myQuestion.generalInfo.label = "changed";
        console.log("change attempted");
    }
}

Eventually, I anticipate substantial interaction with the passed objects in the QuestionComponent. My initial approach was to pass the Question object into the constructor directly, but that didn't seem feasible. For now, I implemented the onClick button to experiment with modifying an @Input'ed variable.

The child component's template unfolds like this:

<div *ngIf="!justText">
    no text passed
</div>
<div *ngIf="justText">
    <b>Here is the passed Text:</b><br>
     {{justText}} <br>
</div>
<br>
<div *ngIf="!justObj">
    no obj passed
</div>
<div *ngIf="justObj">
    <b>Here is the passed JSON:</b><br>
     Foo: {{justObj.foo}} <br>
     Baz: {{justObj.baz}}
</div>
<br>
<div class="question">
    <i>I am a question spot</i>

    <div *ngIf="!myQuestion">
        Loading Question...
    </div>
    <div *ngIf="myQuestion">
        <b>Here is the passed question:</b><br>
         {{myQuestion}} <br>
    </div>
</div>

<button (click)="onClick()">Clickit</button>

How can I access the @Input'ed objects within the class? Specifically, how do I modify "myQuestion" in the 'onClick()' function? Furthermore, how can I ensure that changes to the objects reflect on the view?


Notably, I've attempted to pass the value from the 'view' back through the onClick call by altering the button to:

<button (click)="onClick(myQuestion)">Clickit</button>

And adjusting onClick to:

onClick(q) { q.generalInfo.label = "changed"; }

This attempt did not yield the desired outcome.

Answer №1

I feel foolish.

After spending several hours researching and looking (prior to asking), the solution boiled down to simply adding "this".

... like

"myQuestion.generalInfo.label = "changed";"
should have been
"this.myQuestion.generalInfo.label = "changed";"

Programming can be quite tricky at times, huh?

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

The error message "system.js:4 Uncaught (in promise) error" popped up unexpectedly as I was working on my ES

I'm dipping my toes into ES6 development using Plunker. I've loaded Traceur and SystemJS, but I'm encountering the following errors: GET https://traceur-compiler.googlecode.com/git/bin/traceur.js 404 () VM490 system.js:4 GET https://run.pln ...

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is p ...

What is the method to display just the final 3 characters within a paragraph?

Is there a way to display only the last three characters of a string using either a method or a string method? I consistently have a 13-digit number, but I specifically require showing only the final three digits. Appreciate any assistance provided. Than ...

Update the WooCommerce shopping cart page automatically upon product removal

After trying to solve the issue of refreshing the cart page in WooCommerce when a product is removed, I came across this helpful question on Stack Overflow: Refresh the page after product remove from cart Woocommerce. Following the provided code snippet th ...

How can JSON be best connected in Angular for optimal performance?

My JSON structure is as follows: { items:[], errors:[], foundItems:9 } One part of my program requires access to "items", while another part needs access to "errors." To resolve this issue, I decided to create a new interface and a new class to hand ...

The efficiency of XSL Template is significantly impacting loading time

Hello there, I am facing a challenge with my webpage's loading speed due to the code provided below. Can you assist me in optimizing it? <xsl:template match="Category" mode="CategorySelectorScript"> <xsl:variable name="ThisCateg ...

How can I pass arguments from a Python command line program (compiled to an EXE) to a JavaScript file?

As I work on developing a node program, I've come across certain abilities that Python possesses which JavaScript lacks, such as utilizing Python-specific modules. To bridge this gap, I made the decision to compile Python files into EXE and then invok ...

Deactivate a function when the dropdown input is selected

I'm currently using a function to attach scroll events to a slider element for navigating through slides. However, I want to temporarily disable this function in specific situations - such as when a dropdown is in focus - to allow smooth scrolling thr ...

The controller method appears to be unable to detect any parameters

I have been trying to pass an ID in the URL but my controller is not receiving that value. $("#ChangeSlideForm").on("submit", function(){ $.ajax({ type: "POST", url: base_url + "Visualiser/ChangeSlide/21", su ...

Encountering a Typescript Type error when attempting to include a new custom property 'tab' within the 'Typography' component in a Material UI theme

Currently, I am encountering a Typescript Type error when attempting to add a custom new property called 'tab' inside 'Typography' in my Material UI Theme. The error message states: Property 'tab' does not exist on type &apos ...

Maximizing the potential of Angular forms through native FormData

Currently, I am revisiting an older project that still uses traditional methods for form submission. The HTML includes a form element with defined method and action. My goal is to submit the form in the old-fashioned way using the action attribute to post ...

Use radio buttons to enable switching between different data options within a dropdown menu

I am working on a dropdown box that is populated dynamically using JSON data. The content in the dropdown can be categorized into 4 types, so I have included radio buttons to switch between these categories. I have created HTML code to toggle between manu ...

Utilizing the `this` keyword within a click handler that is passed through an intermediary function

If I initially have a click event handler in jQuery set up like this jQuery('#btn').click(_eventHandler); And handling the event as follows function _eventHandler(e){ jQuery(this).text('Clicked'); } Does the this keyword serve a ...

Unable to retrieve element using getElementById with dynamically assigned id

After researching on Google and browsing through various Stack Overflow questions (such as this & this), I have not been able to find a solution. I am currently working on validating dynamically generated rows in a table. The loop and alert functions a ...

Tips for enhancing a search algorithm

I am currently working on implementing 4 dropdown multi-select filters in a row. My goal is to render these filters and update a new array with every selected option. Additionally, I need to toggle the 'selected' property in the current array of ...

Troubleshooting: Else block not functioning as expected within a React JS map function

I have a notification feature that makes an API call every 10 seconds to display an alert based on the response. However, I'm encountering an issue where the div is not being rendered properly. The div should be displayed based on certain conditions w ...

Searching for an item in an array within MongoDB: Tips and techniques

I am attempting to locate the object containing a specific element within an array: Here is my query: router.get('/', function(req, res) { var userSubscribed = req.user.email; db.posts.find({ "SubscriberList": { $elemMatch: userSubscrib ...

Aligning the stars with CSS

One of the components I have deals with a star rating system, and I thought it would be cool to use Font Awesome icons for half stars. Everything is working well except for the CSS styling aspect. While I managed to position some of the stars correctly by ...

Issues with premature execution of Angular JS code have been observed at times

Currently facing an issue with my code where the updateProduct() function call is happening before the forEach loop begins running on about 1 out of every 10 page loads. Not sure why this is occurring or how to solve it. Any insights on what might be causi ...

Unit testing in Angular JS is crucial, especially when testing functions in services that do not return any values

Apologies if this has been asked before, but I couldn't find a solution to my issue. I need to create tests for a service within an Angular JS application. The main function of the service returns and is used as an external method. There are also a ...