Updating an object property within an array in Angular Typescript does not reflect changes in the view

I am currently delving into Typescript and Angular, and I have encountered an issue where my view does not update when I try to modify a value in an array that is assigned to an object I defined. I have a feeling that it might be related to the context being lost here. Should I somehow execute ngZone? (I've already attempted without success). It seems like there may be a simple solution or a concept that I might be missing.

cardItems = {
  addUser: true,
  inventory: false
}
cardCollapseItems = [
{
  label: "addUser",
  item: this.cardItems.addUser
},
{
  label: "inventory",
  item: this.cardItems.inventory
},

collapseCard(value){
 let index = this.cardCollapseItems.findIndex(item => item.label === value)
 let cardItem = this.cardCollapseItems[index]
 cardItem.item ? cardItem.item = false : cardItem.item = true;
}

 <ion-card-header (click)="collapseCard('addUser')">
 <ion-card-content [hidden]="cardItems.addUser" >

Answer №1

Here is a solution you can try out:

Step One:

@Component({
  selector: 'app-example-page',
  templateUrl: './example.page.html',
  styleUrls: ['./example.page.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})

Step Two:

public cdRef: ChangeDetectorRef;

public constructor(
    cdRef: ChangeDetectorRef,
  ) {
    this.cdRef = cdRef;
  }

collapseCard(value){
 let index = this.cardCollapseItems.findIndex(item => item.label === value)
 let cardItem = this.cardCollapseItems[index]
 cardItem.item ? cardItem.item = false : cardItem.item = true;
 this.cdRef.detectChanges();
}

Answer №2

To properly display the cardItems in your view, you need to update it within the collapseCard function. By updating it with this.cardItems, you will be able to resolve the issue. Assigning a boolean value to a variable that is only accessible within the function's scope may cause limitations.

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 methods are available to restrict the values of properties to specific keys within the current type?

I am looking to declare an interface in typescript that is extensible through an indexer, allowing for the dynamic association of additional functions. However, I also want sub properties within this interface that can refer back to those indexed functio ...

Tips for formatting JSON using jQuery

Imagine my JSON data with 3 different sets of information: [ { "Pair":"", "Id":"8ca2df56-2523-4bc3-a648-61ec4debcaaf", "PubDate":"/Date(1463775846000)/", "Provider":null, "Market":"" }, { "Pair":"", ...

Manipulating content with JavaScript in Internet Explorer using the outerHTML property is a powerful

Encountering an Issue with outerHTML in IE Browser If I try the following: txt = "Update Complete!"; msg = sub.appendChild(d.createElement("p")); msg.outerHTML = txt; It works without any problem. However, if I use: txt = "1 Error:<ul><li> ...

Updating state in React with a nested promise within the useEffect hook

Trying to update the component state using React.useState with the help of useEffect. The reason behind using useEffect is that the API call response (EmployeeState > init()) determines what gets displayed on the UI. Component: import { EmployeeState } ...

"Utilize Tuple in TypeScript to achieve high performance programming

I've been delving into TypeScript, focusing on the tuple type. As per information from the documentation, here is the definition of a tuple: A tuple type is another form of Array type that precisely knows its element count and types at specific posi ...

The `mouseenter` event handler fails to trigger properly on its initial invocation

As I work on a function to remove a CSS class display:hidden; when the mouse enters a specific part of the DOM to reveal a menu, I encounter an issue. Upon loading the page and hovering over the designated area for the first time, the event fails to trigge ...

New in the world of JavaScript: A method that replicates the functionality of jQuery's

Take a look at this JSFiddle example: https://jsfiddle.net/1a6j4es1/1/ $('table').on('click', 'td', function() { $(this).css('background', 'green'); }); How can you rewrite this code using plain JavaS ...

Having trouble setting up a new Angular project using NodeJS?

I am encountering an issue while attempting to create a project following the installation of angular-cli on my system. Upon running the command ng new project-name, I am faced with the following error message: ERROR: 21328 verbose stack Error: EPERM: ...

Cypress 7: Dealing with the onRequest Problem in the cy.intercept Function

We encountered a situation where we needed to assert that a spinner was displayed during a request using the following code: The code functioned properly in Cypress 6.4.0 cy.intercept({ url: '*', onRequest: () => { cy.get('[data- ...

The benefits of exporting a component from one module and using it in another module

After putting in long hours trying to figure this out on my own, I've finally decided to seek help from the community. Thank you in advance for any assistance! I have a Web Projects Module that utilizes a Webpage Component. Within the Webprojects Mod ...

Unable to display content within a map function

I am facing an issue with a map function in my code. The function is supposed to return a component with deconstructed properties. While the map itself is functioning correctly and I can see all the right values when I log them to the console, nothing is g ...

Can you provide instructions on utilizing WYSIWYG for real-time label editing?

I am currently developing an online survey creator. The structure of a Question entity is as follows: [Question] int QuestionId { get; set; } int QuestionNumber { get; set; } String QuestionText { get; set; } QuestionType QuestionType { get; } When prese ...

Having trouble activating the ENTER key press event listener for the QuillJS editor in Angular 4 and above

I have been trying to set up an event listener for the ENTER key press in QuillJS using addBinding as described in the official documentation here. However, despite successfully configuring listeners for other keys like BACKSPACE, I am unable to get the EN ...

Having trouble getting collision events to trigger in ThreeJS when using the PhysiJS physics engine?

When an object falls and collides with the ground, an alert box should pop up displaying the message "Box just hit the ground". However, there seems to be an issue as the alert box is not being created upon collision. Additionally, no relevant JavaScript ...

Tips for accessing user input in JavaScript functions

In my ASP.NET code, I have created a dynamic image button and panel. Here is the code: Panel panBlocks = new Panel(); panBlocks.ID = "PanBlockQuestionID" + recordcount.ToString(); panBlocks.Width = 1300; panBlocks.Height = 50; panBlocks.BackColor = Color. ...

Create a new storefront JavaScript plugin for Shopware 6 to replace the existing one

I am attempting to replace an existing JavaScript plugin in Shopware 6. However, the code within the plugin file does not seem to execute. Here is my main.js: import MyCookiePermissionPlugin from './plugin/my-cookie-permission/my-cookie-permission.pl ...

Surprising outcomes arise when the results of Three.js EffectComposers are combined, as the Additive and Subtractive effects interact in unexpected

While working on postprocessing in Three.js with EffectComposers and shader passes, I encountered some unexpected behavior when combining the WebGLRenderTargets (renderTarget2) from different composers. My setup involves five composers: three to render sce ...

Ways to trigger an event based on the outcome of a pop-up window

In my current project, I am working on a component that includes three buttons: two default options and an additional modal dialog option for more advanced choices. When one of the default buttons is clicked, the component emits an event based on the selec ...

Angular8's NgFor directive is designed to bind to Iterables like Arrays only

Having an issue retrieving data from Github and displaying it, as I am encountering errors. The code editor is highlighting an error with "followers" in the github-followers.component.ts file. githup-followers.component.html <div *ngFor="let follower ...

Express.js does not display console.log messages while routing

Just starting to explore Express and its middleware functions. var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send('id: ' + req.params.id + ' and name: ' + req.param ...