Modifying the user interface (UI) through the storage of data in a class variable has proven to be

If I need to update my UI, I can directly pass the data like this:

Using HTML Template

<li *ngFor="let post of posts; let i = index;">
  {{i+1}}) {{post.name}}
<button (click)="editCategory(post)" class="btn btn-danger btn-sm">Edit</button>
</li>

Using Component TS

editCategory(post){
  post.name = "Something";
}

This method reflects the changes in the UI and works as expected. However, when trying to make changes indirectly, it doesn't work as follows:

Using HTML Template

<li *ngFor="let post of posts; let i = index;">
{{i+1}}) {{post.name}}
<button (click)="deleteCategory(post); modal1.show();" class="btn btn-danger btn-sm">Edit</button>
</li>
<div #modal1="bs-modal">
<button (click)="finallyDeleteCategory(); modal1.show();" class="btn btn-danger btn-sm">Edit</button> //making changes through this button
</div>

Using Component TS

deleteCategory(post){
  this.savedPost=post;
}

finallyDeleteCategory(){
  this.savedPost.name="deleted"; //this Doesn't work
}

Storing data in a class variable and then making changes to it does not reflect in the UI.

Questions:

  1. How do I store the reference of the Post in a class variable?
  2. Is this the correct way to make changes indirectly or should I pass on data in the HTML itself?

Any assistance would be greatly appreciated, thank you!

Answer №1

It is important to note that since finallyDeleteCategory is outside the loop context, passing a reference of post and changing its name directly will not work as it does not exist in that scope.

Attempting to use this.savedPost.name="deleted"; within the loop does not work due to the elements being part of the posts array. Instead, you can save the index i of the post object and utilize it in your method like:

(click)="editCategory(i)"

deleteCategory(loopindex){
 this.index=loopindex
}

In the finallyDeleteCategory method, you can retrieve the posts from the array using the saved index and then make changes to the post object directly.

finallyDeleteCategory(){
  posts[this.index].name="deleted";
}

Answer №2

Based on your current configuration, the deleted post will only be saved if you use the 'deleteCategory' method on the list item. In order for the changes to take effect immediately, you need to press the edit button after performing the deletion.

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

'jQuery' is not recognized as defined, error no-undef

I am currently working on a file that utilizes jQuery for testing purposes: (function($) { "use strict"; // Start of use strict // Configure tooltips for collapsed side navigation $('.navbar-sidenav [data-toggle="tooltip"]').tooltip({ ...

The current date is cycling back to the month before

There is a datetime received from my api as 2018-09-01T00:00:00.000Z, referred to as frame.scandate. Another date is generated within the program as 2018-09, simply known as scandate. These examples can represent any year/month combination. In my code: ...

What is the best library to utilize for uploading an Excel file in a React application?

As a beginner in JS and React, I have a simple question that I hope someone can help me with! I am trying to figure out how to upload an excel file using a form and then extract the data from the rows and columns. For example, I would like to calculate th ...

Combine various input data and store it in a variable

I am looking for a way to add multiple input text values together and store the sum in a variable. Currently, I can add the values and display it in an id, but I want to assign it to a variable instead. The condition for this variable is described below af ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

The issue of HTTP parameters not being appended to the GET request was discovered

app.module.ts getHttpParams = () => { const httpParamsInstance = new HttpParams(); console.log(this.userForm.controls) Object.keys(this.userForm.controls).forEach(key => { console.log(this.userForm.get(key).value) const v ...

Identifying Flash content in a unique way

In my dynamic page (let's call it myFlashContainer.jsp), the Flash content changes based on the link that is clicked. The code responsible for rendering the Flash looks like this: <object height="100%" align="l" width="100%" id="player" codebase= ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

AmCharts stacked bar chart - dynamically adjust value visibility (adjust transparency) based on user interaction

I recently utilized amcharts to construct a bar chart. The creation of my stacked bar chart was inspired by this specific example. Currently, I am attempting to modify the alpha (or color) of a box when hovering over another element on my webpage, such as ...

The function upgradeDom() from vue mdl componentHandler is not returning a valid function

Attempting to integrate mdl into a vue.js project (using vue v2.1) and encountering a familiar issue to that discussed here. However, when I include mounted () { componentHandler.upgradeDom()} in my App.vue, I am receiving the following error: TypeError: ...

What is the proper way to integrate helmet.js with typescript?

Utilizing helmet from pure JavaScript according to the documentation is quite straightforward: const express = require('express') const helmet = require('helmet') const app = express() app.use(helmet()) However, I'm unsure how ...

Validate input strings in Node.js using Joi to detect and return an error if there are leading or trailing spaces

Looking to set up JOI validation in Node.js that flags errors if a string begins or ends with an empty space. For example: name = "test123" //valid name = "test(space)" or "(space)test" // invalid ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

When utilizing a personalized Typescript Declaration File, encountering the error message 'Unable to resolve symbol (...)'

I'm having trouble creating a custom TypeScript declaration file for my JavaScript library. Here is a simplified version of the code: App.ts: /// <reference path="types.d.ts" /> MyMethods.doSomething() // error: Cannot resolve symbol "MyMetho ...

Ways to transfer an Object from a service to a component

I'm currently working on my website and trying to implement a cart feature where users can add items. To achieve this, I have created a service that contains the cart as an object called cart. The service has functions to add items to the cart and ret ...

Express router fails to mount

Struggling with my first project using expressjs, I have encountered an issue with a router not properly mounting. My approach involves the app mounting a router object which should then mount a second router object. While the first embedded router mounts ...

How to easily update a URL string in Angular 5 router without altering the state of the application

I am working on an Angular 5 application that utilizes the angular router. The majority of my entry route components are placed under a context id, which represents a name in the app store along with other relevant data for that context. Even though the na ...

Discover the correct way to locate the "_id" field, not the "id" field, within an array when using Javascript and the MEAN stack

I am working on an Angular application that connects to MongoDB. I have a data array named books, which stores information retrieved from the database. The structure of each entry in the array is as follows: {_id: "5b768f4519d48c34e466411f", name: "test", ...

Is there a different way to invoke PHP within JavaScript?

Is it possible to include PHP code in JavaScript? I have come across information stating that this practice is not recommended: document.getElementById('id1').innerHTML="<?php include my.php?>"; If including PHP directly in JavaScript is ...

Input a value to request in the Mssql node

I am using angular2 and mssql to establish a connection with SQL Server. This is my code snippet: var express = require('express'); var app = express(); var sql = require("mssql"); // database configuration var config = { user: 'sa&ap ...