Concealing a specific element within an ngFor loop in Angular 5

My ngFor loop in Angular 5 generates a series of cards. Each card has a button that, when clicked, should hide only that specific card. However, the issue is that clicking on one button hides all the cards. Here is the click event handling function:

 removeUserLikedProperty(property_id: string) {
    this._user.removeUserLikedProperty(property_id);
    this.hidden = !this.hidden;
    console.log(property_id)
  }

Here is the button used to trigger the hiding functionality:

 <button class="button button-previous" (click)="removeUserLikedProperty(property?.property_id)">unlike</button>

And here is the for loop with the [hidden] attribute binding:

     <section *ngIf="properties; else noItems">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-4" *ngFor="let property of properties" >
        <div class="card" [hidden]="hidden">
          <div class="card_header" [routerLink]="['../../' + routes.Tenant.rent_property, property?.property_id]">
            <img src="{{property?.property_photos[0].image_url}}" class="image no-buttons property-card__carousel"
                 *ngIf="property?.property_photos?.length; else noImageUploaded">
            <ng-template #noImageUploaded>
              <img src="/assets/img/icons/camera.png" alt="" style="height: 250px; width: 100%; padding: 25px">
            </ng-template>
          </div>
          <div class="about">
            <div class="row">
              <div class="col-md-6">
                <div class="property-type" *ngIf="property?.description">{{property?.bedrooms?.length}} Bed
                  {{property?.property_type}}
                </div>
              </div>
              <div class="col-md-6 text-right">
                <div class="icons" *ngIf="property?.bedrooms?.length > 0 || property?.bathrooms">
                  {{property?.bedrooms?.length}}<img
                  src="/assets/img/icons/Double-Bed/Double-Bed.png" alt="" class="icon_default icon">
                  {{property?.bathrooms}} <img
                  src="/assets/img/icons/En-Suite-Bathroom/En-Suite-Bathroom.png" alt="" class="icon_default icon">
                </div>
              </div>
            </div>
            <p class="address"> {{property?.street_number}}, {{property?.first_line_address}}
              <br>
              {{property?.city}},
              {{property?.post_code}}
            </p>
            <div class="row">
              <div class="col-md-6">
                <p class="price">&pound;{{property?.rent_pcm}} pcm <br>
                  <span class="bills" *ngIf="property?.is_bills_included">including bills</span>
                  <span class="bills" *ngIf="!property?.is_bills_included">including bills</span>
                </p>
              </div>
              <div class="col-md-6 text-right">
                <p class="address"> Listed</p>
                <div class="date">{{property?.date_listed | date}}</div>
              </div>
            </div>
            <hr>
            <p class="featured" *ngIf="property?.feature_tags"> {{property?.feature_tags}}</p>
            <button class="button button-previous" (click)="removeUserLikedProperty(property?.property_id)">unlike</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

The problem persists where clicking on any button hides all cards instead of just the selected one. Does anyone have suggestions on how to fix this behavior?

Answer №1

All cards on this platform are designed to have the same '[hidden]=hidden' attribute. Therefore, when you adjust the 'hidden' attribute to 'false', all cards will disappear simultaneously.

My suggestion would be something like the following:

<card *ngFor="let card of userCardList">
    ...
    <button (click)="removeCardFromUserList(card)">Remove</button>
</card>

removeCardFromUserList(card) {
    let index = userCardList.indexOf(card);
    userCardList.splice(index, 1);
}

This approach involves maintaining a list of visible cards rather than toggling hidden/visible flags individually for each card. By removing an item from the visible cards list, it will automatically vanish from the page. Adding an item to the list will display it. This eliminates the need for [hidden] or *ngIf directives in the card element's view code. Consider keeping one master list of all cards and a separate list for the user's active cards.

Another solution could be implementing something like 'property.visible = false' if you are working with property objects. Simply add an attribute to control visibility within the object, which might simplify your setup.

Answer №2

Instead of removing items from a list, consider using an object structure like this initially:

userCardList = [{
'visibility': true,...
}, {
'visibility': true,...
},...]

Simply hide the card by setting the 'visibility' property to false when clicked.

<card *ngFor="let card of userCardList" *ngIf="card.visiblity">
    ....
    <p class="featured" *ngIf="property?.feature_tags"> 
        {{property?.feature_tags}}
    </p>
    <button (click)="card.visiblity = false">
        Remove
    </button> 
</card>

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

Discovering Spring Boot Properties Within Angular Application

Situation: One microservice is built using Spring Boot and Angular 8. In the Spring Boot application, there is a properties file called application.yaml with the following content: url-header: http gateway: host: envHost:envPort ui-endpoints: g ...

Can the serialization of a user be avoided while connecting an account in PassportJS?

My application allows users to establish multiple oAuth connections to their account through PassportJS. Every time I connect another app using the Mailchimp strategy and Salesforce strategy, it logs me out of my session with Express. It seems like Passpo ...

What databases are accessible on the client-side in JavaScript, excluding those that are specific to certain

Seeking information on available non-browser (HTML 5) specific databases for JavaScript client-side programming. ActiveX controls are not preferable. ...

Searching for data in Node.js using Mongoose and dates

I'm in search of a way to execute a specific query with mongoose. In my mongodb database, I have data structured like this: "startDateTime" : ISODate("2017-03-22T00:00:00.000Z"), "endDateTime" : ISODate("2017-03-27T00:00:00.000Z"), My goal is to r ...

The custom directive fails to display the value of {{variable}}

Here is the Angular controller setup: app.controller("timelineCtrl", function ($scope) { $scope.user="john"; . . . } This directive is also in place: app.directive('helloWorld', function() { return { ...

My collection contains a <List /> of row elements with varying DOM heights

When dealing with a react-virtualized List that has variable content in each row, calculating the DOM height using a rowHeight function can be a challenge. Since this function is called before the row is rendered, it may be difficult to accurately determin ...

Encountering problems with parsing a lengthy JSON file

Can you spot the issue here? let stringinsta = JSON.parse({ "access_token":"129261**5ea59a4da481c65", "user":{ "username":"carlos_bellesso", ...

Guide on creating a message string by incorporating array values where available

I'm trying to show a warning to the user. I have an array that I split, and I always use the values in positions 0 and 1. Occasionally, there might be a value in position 2, but not always. I want to create a message string that displays the value of ...

A guide to implementing toggle functionality on child elements

After clicking the button, the entire sidebar toggles, but I only want the side menus to toggle. Here is the relevant HTML code: <nav id="sidebar"> <div class="sidebar-header"> <img src="/fintantra/image ...

Error message: Component is unable to access the $store property because it is undefined

After doing extensive research and reading numerous similar questions on various platforms, I am still unable to resolve my issue. I have a component containing a login form that triggers a method to dispatch a $store action for logging in the user via fi ...

Re-executing PHP script using AJAX on the existing webpage

I am facing a rather intricate issue. Currently, I am in the process of constructing a page that searches tags in a MySQL table and displays results without any reloading or redirection. The tags are user-input and managed using JavaScript. Let me outline ...

Modify form content by utilizing a VueJS method

Currently, I am utilizing VueJS and facing a challenge with a form that consists of two fields. The first field requires user input, while the second field should calculate its value by passing the input from the first field through a method. HTML <di ...

Can anyone provide assistance on implementing multiple where conditions in a loop with Firebase and Angular?

I've been attempting to implement dynamic conditions on a firebase query, but I'm having issues getting it to work. I even tried using chatgpt, but that didn't provide me with the ideal solution either. Can someone please assist me in resolv ...

Integrating AWS IVS quality plugin with video.js for enhanced video streaming in a Next JS application

Hello, I am new to AWS media services and recently started experimenting with AWS IVS for video streaming. I am currently working on integrating the AWS IVS quality plugin to Video.js. The player is up and running, displaying the video, but I encountered a ...

Reduce the speed of horizontal scrolling in a div element

I have a container with 3 lines of text, and each line is wider than the container itself. This causes a horizontal scrollbar to appear, but I've hidden it. My goal is to slow down the scrolling speed for this particular element. Here is a fiddle: ht ...

Experiencing issues with utilizing long polling on a node.js server URL in Internet Explorer

Currently, I am in the process of testing an application that utilizes long polling with jQuery to query a server built with node.js. The code for long polling is as follows: (function poll(){ $.ajax({ url: "http://localhost:3000/test", ...

Display the element once the class enters the viewport

I am attempting to display a div only when certain elements with a specific class are visible in the viewport. I made progress with this example: http://jsfiddle.net/blowsie/M2RzU/ $(document).ready(function(){ $('.myclass').bind('inv ...

To ensure compatibility with Angular, the data path "/fileReplacements/1/replace" should adhere to the pattern ".(([cm]?j|t)sx?|json)$"

After upgrading Angular from version 10 to 14, I encountered an issue in the build process related to replacing the favicon.ico using fileReplacements like so: "fileReplacements": [ { "replace": "src/favicon.ico", ...

Display a pop-up window upon clicking anywhere on the webpage using jQuery and HTML

Is it possible for me to create a pop-up window that opens a specific website when a user clicks anywhere on the page, similar to pop-up companies? Can this be achieved using HTML, JavaScript, and jQuery? Any help would be greatly appreciated. ...

Updating entire DOM in javascript

Implementing undo-redo functionality in my project has proven to be quite complex, as every change affects numerous elements. I believe that saving and restoring the entire page may be the most effective solution. However, I have encountered issues with mi ...