Display the ion-button if the *ngIf condition is not present

I am working with an array of cards that contain download buttons. My goal is to hide the download button in the first div if I have already downloaded and stored the data in the database, and then display the second div.

<ion-card *ngFor="let data of itemList.list let i = index">
  <ion-card-content>

    <div> <!-- I want this to display if *ngIf="n == data.task does not display -->
      <ion-button (click)="saveData(data.link)" >Download for offline use</ion-button>
    </div>

    <div *ngFor="let n of loop"> <!-- loops through keys in the database -->
      <div *ngIf="n == data.task"> <!-- if the data.task key exists, the buttons are displayed -->
        <div class = "linkButtons">
          <ion-button (click)="openForm(data.Type, data.task)">&nbsp;&nbsp;Open&nbsp;&nbsp;</ion-button>
          <ion-button (click)="syncData()">Sync</ion-button>
          <ion-button (click)="deleteAudit( n )">Delete</ion-button>
        </div>
      </div>
    </div>

  </ion-card-content>
</ion-card>   

Answer №1

If you're looking to achieve a specific goal using just the template, that might not be possible. You can find more insights on this topic here.

One workaround is to cache the results within your component by utilizing a Map.

dataTasks = new Map<any, boolean>()
taskEquals(data: any, n: any) {
    if (!this.dataTasks.get(data)) {
        this.dataTasks.set(data, data.task == n)
    }
    return data.task == n
}

hasTask(data: any) {
    return !!this.dataTasks.get(data)
}

Subsequently, your template code can make use of these functions:

<ion-card *ngFor="let data of itemList.list let i = index">
  <ion-card-content>

    <div *ngIf="hasTask(data) == false">
      <ion-button (click)="saveData(data.link)">Download for offline use</ion-button>
    </div>

    <div *ngFor="let n of loop">
      <div *ngIf="taskEquals(data, n)">
        <div class = "linkButtons">
          <ion-button (click)="openForm(data.Type, data.task)">&nbsp;&nbsp;Open&nbsp;&nbsp;</ion-button>
          <ion-button (click)="syncData()">Sync</ion-button>
          <ion-button (click)="deleteAudit( n )">Delete</ion-button>
        </div>
      </div>
    </div>

  </ion-card-content>
</ion-card>  

A different approach, without relying on Map, would involve assigning the result to a property on the data object.

Answer №2

If you're looking to incorporate ngIf with else into your code, consider the following adjustment to your template structure:

<ion-card *ngFor="let data of itemList.list">
  <ion-card-content>

    <div *ngIf="n === data.task; else linkButtons">
      <ion-button (click)="saveData(data.link)">
        Download for offline use
      </ion-button>
    </div>

    <ng-template #linkButtons>
      <div *ngFor="let n of loop">
        <div class="linkButtons">
          <ion-button (click)="openForm(data.Type, data.task)">Open</ion-button>
          <ion-button (click)="syncData()">Sync</ion-button>
          <ion-button (click)="deleteAudit(n)">Delete</ion-button>
        </div>
      </div>
    </ng-template>

  </ion-card-content>
</ion-card>

Answer №3

To ensure that data has been downloaded, you can introduce a local boolean flag in the data object. Additionally, modifications to the saveDate(data) function are necessary:

<ion-card *ngFor="let data of itemList.list let i = index">
  <ion-card-content>

    <div *ngIf="data.downloaded">
      <ion-button (click)="saveData(data)" >Download for offline use</ion-button>
    </div><br/>

    <div *ngFor="let n of loop"> <!-- loops through keys in database -->
      <div *ngIf="n == data.task"> <!-- if data.task key exists the buttons display -->
        <div class = "linkButtons">
          <ion-button (click)="openForm(data.Type, data.task)">&nbsp;&nbsp;Open&nbsp;&nbsp;</ion-button>
          <ion-button (click)="syncData()">Sync</ion-button>
          <ion-button (click)="deleteAudit( n )">Delete</ion-button>
        </div>
      </div>
    </div>

  </ion-card-content>
</ion-card>
saveData(data){
    // remaining logic
    data.downloaded = !data.downloaded;
}

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

Steps for creating a copy of an Angular component

https://i.stack.imgur.com/4RMsR.png Whenever the user clicks on the Create Copy button, I aim to replicate the content of the DashboardComponent and position the duplicated version below the original one (the DashboardComponent featuring four dark blue sq ...

Set an array to a JSON object as a fresh entity

My challenge involves working with an array that contains certain values. let myArray = [value1, value2]; I am looking to generate a JSON object in the format shown below: { "field": "[value1, value2]" } ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

The program abruptly shut down with error code 127. Any idea why this occurred?

I'm having issues while attempting to create an app from a script. When I run "ionic serve," the following errors occur: [error] Error: Job name "..getProjectMetadata" does not exist. at Observable._subscribe (C:\Users\Bhanu\Desktop&bs ...

Deploy your Angular2 application with a specified base URL

I am embarking on the journey of Angular2 web app development. After successfully creating an Angular2 application using angular-cli, I am now faced with the challenge of deploying it to my Tomcat server. Following the ng build command, a dist folder was ...

Differences between Angular2 local template variables and Jade ID shortcutsIn Angular2, local

Angular2 has introduced the local template variable feature, which is created using #var. When using the Jade Template Engine, this syntax gets converted to #var="var". Is there a method to avoid this conversion? Otherwise, accessing the original local t ...

Has the Angular 2 community established a standardized ecosystem?

As a developer specializing in Angular 1, I am now eager to dive into the world of Angular 2. However, navigating through the changes and rewrites can feel like traversing a confusing maze. All of the comprehensive guides I have come across date back to l ...

Is there a method to automatically eliminate all unnecessary properties in an Angular project?

In my extensive Angular project, I suspect that there are numerous declared properties in .component.ts that are not being used. Is there a method available to automatically eliminate all unused properties within an Angular project while also taking into ...

Secure higher order React component above class components and stateless functional components

I have been working on creating a higher order component to verify the authentication status of a user. Currently, I am using React 15.5.4 and @types/react 15.0.21, and below is a simplified version of my code: import * as React from 'react'; i ...

Why did the compilation of Next.js using TypeScript and ESLint succeed despite encountering errors?

I've been delving into Next.js and encountered unexpected results when integrating TypeScript and ESLint. ESLint seems to work well with TypeScript, but my project compilation is successful despite encountering errors. It's puzzling why the comp ...

The crosshair functionality in Zing Chart is causing a CPU leak

After enabling the crosshair feature on my chart, I noticed a significant issue when using Chrome 57 (and even with versions 58 and ZingChart 2.6.0). The CPU usage spikes above 25% when hovering over the chart to activate the crosshair. With two charts, th ...

Can a constant value be dynamically defined in Typescript?

Trying to dynamically define a constant in Typescript has proven to be more challenging than I anticipated. Here's what I attempted: define(name: string, value: any): boolean { var undef; const name = value; return name == undef; } ...

Limit the implementation of Angular Material's MomentDateAdapter to strictly within the confines of individual

Within my app, I have several components that utilize the mat-datepicker. However, there is one component where I specifically want to use the MomentDateAdapter. The issue arises when I provide it in this one component as it ends up affecting all the other ...

Tips for effectively managing asynchronous tasks

I keep getting different numbers every time my code runs. Can you tell me if I'm doing this the right way? Here's the code: export class GetPlanetsService { url='https://swapi.co/api/planets/?page='; planets:Planet[]=[]; headers: ...

Experiencing the error "f.ngOnChanges is not a function in target es5" while using Angular4

Encountering an issue f.ngOnChanges is throwing an error The problem arises when my tsconfig.json file is configured to target es5. However, everything works fine if I set the target to es6. Is there a way to make ngOnChange function properly with es ...

What is the best way to reference typescript files without using absolute paths?

As typescript does not seem to have built-in support for absolute path references (according to this GitHub issue), it becomes difficult to organize and maintain my file references. With TypeScript files scattered across various locations in my folder stru ...

Is there a way to effectively sort through Firebase database entries using Angular based on checkbox selection?

I am working on an event page where all events are displayed with a category field. This is how my database structure looks: category: - categoryName events: - eventName - category.id (stores the category id) My goal is to initially display all eve ...

Retrieve all original elements from FormGroup

While working on a Reactive Form in Angular, one of my goals is to enable scrolling within the native element if any control within the form group is invalid. However, there are various other reasons for needing access to the native element, making it just ...

Display the customer's name using the Mat-Select display object property by fetching it from the previously selected or saved value

Having some difficulties with mat-select and options in my Angular 6 project. Here is the scenario I am facing: I would like to create a dropdown list of organizations where I can select one and save the complete organization object, not just its name. ...

Troubleshooting issues with unit testing a component that utilizes a mocked service

I recently delved into testing Angular components and services. After watching a course on Pluralsight, I tried implementing some ideas from the tutorial available at . Unfortunately, I encountered an issue with testing the component method. Despite my eff ...