Clicking the button on an Ionic/Angular ion-item will toggle the visibility of that item, allowing

I'm currently working with Ionic 5 / Angular and I have a collection of ion-item's, each containing a button.

Take a look at the code snippet below:

<ion-list>
    <ion-item>
        <ion-label>One</ion-label>
            <ion-button slot="end" (click)="selfhide()">
                <ion-icon slot="icon-only" name="close-outline"></ion-icon>
            </ion-button>
    </ion-item>
    <ion-item>
        <ion-label>Two</ion-label>
            <ion-button slot="end" (click)="selfhide()">
                <ion-icon slot="icon-only" name="close-outline"></ion-icon>
            </ion-button>
    </ion-item>
    <ion-item>
        <ion-label>Three</ion-label>
            <ion-button slot="end" (click)="selfhide()">
                <ion-icon slot="icon-only" name="close-outline"></ion-icon>
            </ion-button>
    </ion-item>
</ion-list>

The goal is to click on any button and have the respective ion-item hide itself.

For example, clicking on the button in the first ion-item should cause it to disappear.

What would be the best approach to achieve this functionality?

Answer №1

Check out this ngIf solution:

<ion-list>
    <ion-item *ngIf="display.one">
        <ion-label>One</ion-label>
            <ion-button slot="end" (click)="selfhide('one')">
                <ion-icon slot="icon-only" name="close-outline"></ion-icon>
            </ion-button>
    </ion-item>
    <ion-item *ngIf="display.two">
        <ion-label>Two</ion-label>
            <ion-button slot="end" (click)="selfhide('two')">
                <ion-icon slot="icon-only" name="close-outline"></ion-icon>
            </ion-button>
    </ion-item>
    <ion-item *ngIf="display.three">
        <ion-label>Three</ion-label>
            <ion-button slot="end" (click)="selfhide('three')">
                <ion-icon slot="icon-only" name="close-outline"></ion-icon>
            </ion-button>
    </ion-item>
</ion-list>

In your component, include the following code:

display = { one:true, two: true, three: true };


selfHide(item) {
    display[item] = false;
}

Answer №2

Noelmout's solution is solid, but I took a more versatile approach to make the list dynamic. Additionally, I implemented a "show all" button to reveal all items once again.

Here is the content of the component.html:

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

  <ion-list>
    <ng-container *ngFor="let item of items">
      <ion-item *ngIf="item.visible">

        <ion-text slot="start">{{item.name}}</ion-text>
        <ion-button slot="end" (click)="hideItem(item)">
          <ion-icon slot="icon-only" name="close"></ion-icon>
        </ion-button>

      </ion-item>
    </ng-container>
  </ion-list>

  <ion-button (click)="displayAllItems()">
    show all
  </ion-button>

</ion-content>

Below is the corresponding segment from the component.ts file:

import { Component } from "@angular/core";
import { NavController } from "ionic-angular";

@Component({
  selector: "page-home",
  templateUrl: "home.html"
})
export class HomePage {
  public items = [
    { name: "One", visible: true },
    { name: "Two", visible: true },
    { name: "Three", visible: true },
    { name: "Four", visible: true }
  ];

  constructor(public navCtrl: NavController) {}

  hideItem(item: { name: string; visible: boolean }) {
    item.visible = false;
  }

  displayAllItems() {
    this.items.forEach(item => (item.visible = true));
  }
}

I also set up a project on stackblitz for experimentation purposes.

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

Creating a JSON file using an object to send requests in Angular

In my Angular 7 project, I am trying to send a multipart request to the server that includes a file (document_example.pdf) and a json file containing a data object (data_object_example.json). The content of data_object_example.json is as follows: { " ...

Does one require the express.js framework in order to create a web application using nodeJS?

Exploring the creation of a basic web application using HTML, NodeJS, and Postgres. Can this be achieved without incorporating the ExpressJS framework? Seeking guidance on performing CRUD operations with NodeJs, Javascript, and Postgres sans ExpressJS. G ...

What is the method for obtaining the total row of an ngFor loop within an HTML file?

I am trying to figure out how to retrieve the total number of rows in an ngFor loop and display it above. Any suggestions? <p>Total row: "I need to display the number of rows here"</p> <table class="table" > &l ...

Conditionals in Angular 2 using Sass

Looking to apply this style with Sass or CSS: IF :host.form-control MATCHES .ng-valid[required] OR .ng-valid.required THEN :host ::ng-deep input.form-control = border-left: 5px solid #42A948; Appreciate the help! ...

How can I enable editing for specific cells in Angular ag-grid?

How can I make certain cells in a column editable in angular ag-grid? I have a grid with a column named "status" which is a dropdown field and should only be editable for specific initial values. The dropdown options for the Status column are A, B, C. When ...

How can I incorporate percentage values into input text in Angular?

How can I include a percent sign in an input field using Angular, without relying on jQuery? I am looking for a solution that is identical to what I would achieve with jQuery. Here is the current status of my project: ...

Unable to connect to Alpine store from an external source due to a typescript error

Here is how I have configured my Alpine store: Alpine.store( 'state', ({ qr: '' })) Now, I am attempting to update it from an external source as follows: Alpine.store( 'state' ).qr = 'test' However, I am encounte ...

Is there a tool that can automatically arrange and resolve TypeScript dependencies, with or without the use of _references.ts file?

Currently, I am working on understanding the new workflow for "_references.ts" and I feel like there is something missing when it comes to using multiple files without external modules in order to produce correctly ordered ".js" code. To start with, I took ...

What is the process for searching my database and retrieving all user records?

I've been working on testing an API that is supposed to return all user documents from my Mongo DB. However, I keep running into the issue of receiving an empty result every time I test it. I've been struggling to pinpoint where exactly in my cod ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

What methods are available to prevent redundant types in Typescript?

Consider an enum scenario: enum AlertAction { RESET = "RESET", RESEND = "RESEND", EXPIRE = "EXPIRE", } We aim to generate various actions, illustrated below: type Action<T> = { type: T; payload: string; }; ty ...

Display the map using the fancybox feature

I have added fancybox to my view. When I try to open it, I want to display a map on it. Below is the div for fancybox: <div id="markers_map" style="display:none"> <div id="map_screen"> <div class="clear"></div> </div&g ...

Utilize ASP.NET Boilerplate Core and Angular on Microsoft Azure for seamless deployment

I am looking to deploy ASP.NET Boilerplate Core & Angular on Microsoft Azure. The current version of ASP.NET Boilerplate consists of two solutions (one for the backend and one for the frontend), so I need to deploy them on two separate AppServices along wi ...

TypeScript compilation will still be successful even in the absence of a referenced file specified using require

Having both Project 1 and Project 2 in my workspace, I encountered an unusual issue after copying a file, specifically validators/index.ts, from Project 1 to Project 2. Surprisingly, TypeScript compilation went through successfully without showing any erro ...

One way to update the value of the current array or object using ngModel in Angular 2 is to directly

I have a situation where I am dealing with both an array and an object. The array is populated with data retrieved from a service, while the object contains the first element of that array. feesEntries: Array<any> = []; selectedFeesEntry: any; clien ...

Exploring the capabilities of observables in mapping nested dynamic object keys, specifically focusing on manipulating data within angular-calendar events

Perhaps utilizing something like map<T,R> would be a better approach than my current method. I am hoping to receive some advice on how to resolve this issue. Currently, no events are being mapped due to incorrect mapping resulting in an incorrect pat ...

What is a way to construct an object without resorting to casts or manually declaring variables for each field?

Click here for a hands-on example. Take a look at the code snippet below: export type BigType = { foo: number; bar?: number; baz: number; qux?: string[]; }; function BuildBigType(params: string[]) { // Here's what I'd like to do: ...

Establishing foreignObject coordinates in Angular

Struggling with setting the position (x, y) for foreignObject in Angular. I have attempted the following: <foreignObject width="65" height="50" x="{{position?.x}}" y="{{position?.y}}"> <div class="c ...

Assigning union values to an object array: a guide for Typescript

When working with union typed values in an object array, how should the setState() function be implemented? enum SomeStateEnum { IsRunning, Name, } type PersonState = { [SomeStateEnum.IsRunning]: boolean; [SomeStateEnum.Name]: string; }; const st ...