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

Encase the event handler within JQuery

Here's an example of inputs with OnBlur event handlers: <input name="abc" tabIndex="5" class="datetime" onblur="if (CheckMode(this))__doPostBack('abc',''); else return false;" /> Now, in JQuery Form ready function, I want ...

Learn how to seamlessly integrate React Hooks Form with the Select component from @Mui for a powerful

I am currently facing an issue while using react-hooks-form to manage forms in conjunction with the @Mui library. The specific problem I'm encountering is figuring out how to integrate the Select component from the @Mui library with react-hooks-form s ...

What steps should I follow to create a large Angular single page application using ASP.NET MVC?

After gaining some experience with AngularJS on a small project, I am now ready to tackle a larger application. My plan is to create a single-page application using asp.net, making WebAPI calls and loading AngularJS views. However, I am unsure about how ...

What could be causing a case where this.props.posts is undefined in React and Redux

Recently, I attempted to follow a React and Redux tutorial on a blog. However, when working with the PostList component, I encountered an error related to the reducer binding. My main goal was simply to render the renderPost function by calling the reducer ...

Initiating a GET request to execute an SQL query with specified parameters

Let me provide some background information. I am currently using Angular for the frontend and Express for the backend, while also learning how to effectively utilize both technologies. In my application, there is a parent component that generates a group ...

Using jQuery to organize object properties based on the value of another property

Within my collection, I have an array of objects structured as shown below. [ {"rel_id": 1,"forward_flag": true,"asset_id":5,}, {"rel_id": 1,"forward_flag": true,"asset_id":8}, {"rel_id": 1,"forward_flag": false,"asset_id":3}, {"rel_id": 2,"forwar ...

Creating a custom AngularJS HTTP interceptor that targets specific URLs

Is there a way to configure an $http interceptor to only respond to specific URL patterns? For example, I want the interceptor to only intercept requests that match "/api/*" and ignore any other requests. ...

Typescript is issuing warnings when displaying errors for the RTK query

I am currently using React Ts and Rtk query. My goal is to display the API response error on the UI. While it's working, I am encountering a warning that prompts me to set an error type for the response errors. How can I incorporate an error type for ...

When the remove button is pressed, I want the checkbox to become unchecked

I need help with unchecking a checkbox after confirming the removal of items. Can someone provide guidance on how to achieve this? Below is the code I am using: JavaScript: $(".rem-btn").click(function(){ var remConf = confirm("Are you sure you ...

What is the process to ensure a React JS click handler updates the DOM upon execution?

I have almost completed a demo app using React JS, where data is displayed in a table. In the status column, hovering over an item triggers a popup div with 3 options to click on. After clicking on an option, I am able to run the click handler, but I' ...

Tips for sending and retrieving parameters using the POST technique

Currently, I am in the process of building a user authentication form for my website using Javascript. I am utilizing Vue JS on the client-side and NodeJS with ExpressJS on the server-side. For the server-side functionality, I have implemented the followi ...

Encountering TypeScript errors when trying to reference Angular2 within a Gulp setup

The issue at hand is: [11:16:06] TypeScript: 103 semantic errors [11:16:06] TypeScript: emit succeeded (with errors) I am currently using node v5.7.0 and npm 3.6.0 gulp -v: [11:26:58] Requiring external module babel-register [11:26:58] CLI version 3.9 ...

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

Include the url of the html file in your JavaScript code

I have a piece of code that I want to include in my JavaScript instead of HTML. The code is as follows: <script async src="https://www.googletagmanager.com/gtag/js?id=ID"></script> Since all my functions are written in JavaScript, I ...

Is there a similar feature to RxJs version 4's ofArrayChanges in RxJs version 5?

Currently utilizing Angular2 and attempting to monitor changes in an array. The issue lies with only having RxJs5 available, which appears to lack this specific functionality. ...

Using Jquery to loop through various select options within a designated container div

I am seeking a way to loop through multiple select options within a specific div using the jQuery each function. If any field is left empty during this iteration, I would like the loop to break and set the reqCourseFlag variable to 0. The current implement ...

Is it possible to pass an HTML element's id attribute to a function in JavaScript?

In the following code snippet, I am looking to send the id=content to the function mr and then display the result in the passed id=result. While this functionality is currently limited to this HTML file, I aim to extend it to other HTML pages by adding the ...

Exploring AngularJS and Jasmine: Testing a controller function that interacts with a service via $http

I encountered an issue while testing a controller that relies on a service. The problem arises because the service is currently set to null in order to focus solely on testing the controller. The current test setup is failing due to the BoardService being ...

What is the best way to utilize the useSWR hook when there are necessary logical operations to be performed on the response before proceeding with the next API call

I am currently utilizing the swr library in a Create React App and require the usage of the useSWR hook for data fetching that is both contingent and conditional. The specific task at hand involves: Making an API call to retrieve an id which will be used ...

The data structure does not match the exact object type

Why isn't this code snippet functioning as expected? It seems that 'beta' has keys of type string and their values are compatible (id is a number type, and temp is also a number type). Additionally, the Record function should make the values ...