Learn how to dynamically change the state of a button by using the *ngIf directive

For the code snippet below, my objective is as follows:

If the index equals 0, then the button's text should be "info" and it should be enabled.

Also,

If the index equals 1, then the button's text should be "INFO" and it should be disabled. 

Please review my attempt below and provide feedback on the solution:

Code:

<td *ngFor="let application of applications; let index=index">
    <p> 
        <button (click)="showInfoWindow(application)" class="btn btn-sm btn-primary"
        *ngIf = "index == 1; else INFO">info</button>
    </p>
    <ng-template #INFO disabled>
        INFO.
      </ng-template>
</td>

Answer №1

To apply the condition and enable/disable the button, you can use a ternary operator for the label and the [disabled] property. In JavaScript, you can take advantage of the fact that 0 is falsy.

Give this a try:

<td *ngFor="let application of applications; let index=index">
  <p> 
    <button (click)="showInfoWindow(application)" [disabled]="!!index" class="btn btn-sm btn-primary">
      {{ !!index ? 'INFO' : 'info' }}
    </button>
  </p>
</td>

Update: Using *ngIf

<td *ngFor="let application of applications;let index=index">
  <p> 
    <button *ngIf="index; else enabled" (click)="showInfoWindow(application)" disabled class="btn btn-sm btn-primary">
      INFO
    </button>
    <ng-template #enabled>
      <button (click)="showInfoWindow(application)" class="btn btn-sm btn-primary">
        info
      </button>
    </ng-template>
  </p>
</td>

Here's a working example: Stackblitz

Update: Debugging the current index

Rather than using console.log to debug, consider directly rendering the index in the template for quicker access.

<td *ngFor="let application of applications; let index=index" style="padding: 5px; border-right: 1px solid #000000;">
  Current index: {{ index }}
  ...
</td>

If you still want to print to console, create a function in the controller and pass the index to it using interpolation.

Controller

printIndex(index: number) {
  console.log(index);
}

Template

<td *ngFor="let application of applications; let index=index">
  {{ printIndex(index) }}
  ...
</td>

However, be cautious as this approach may lead to multiple function calls during change detection cycles with the default strategy.

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

JavaScript Animation of Text

I have a challenge where I want to animate text's opacity in JavaScript after the user presses enter. However, I am struggling to achieve this with my current code. I can provide all of my code for you to review and help me understand why the animatio ...

Minicart.js - Products successfully added to cart but cart fails to appear on screen

Currently, I am facing an issue with my button click function that is supposed to add an item to the cart using the Minicart.js library from minicartjs.com. Although items are successfully being added to the cart upon clicking the button, the cart itself i ...

Error 403 occurs after submitting the form

Recently, I encountered a 403 error when attempting to submit the form on this page. Interestingly, when I directly accessed the new page by typing the URL into my browser, it loaded without any issues. The PHP code in the initial page looks like this: & ...

Accessing a Kendo Grid instance within an Angular directive

Continuing from the previous question, which can be found here, I have an additional query that I felt warranted a separate post. The link provided above demonstrates how to obtain a grid instance in Angular, credit to Lars for that. Building upon the ex ...

Switch back emulation when moving away from page - using angular javascript

I have a unique scenario in my component.ts file on a specific page where I need to incorporate custom CSS for printing purposes: @Component({ selector: "dashboard", templateUrl: "./dashboard.component.html", styleUrls: ["./d ...

Upon the image being clicked, the form will be automatically submitted

Check out my code snippet: <form action="telecallerinfo.php?action=modify&id=<?php echo $id;?>" method="post" enctype="multipart/form-data"> <table class="panel1"> <tr> <td>Caller Name:&nbsp;<input name ...

Experimenting with Nuxtjs application using AVA and TypeScript

I'm in the process of developing a Nuxt application using TypeScript and intend to conduct unit testing with AVA. Nonetheless, upon attempting to run a test, I encounter the following error message: ✖ No test files were found The @nuxt/typescrip ...

Remove the Ajax-SliderExtender upon refreshing the page with the F5 key

While working with an Ajax SliderExtender in an UpdatePanel, I assigned a BehaviorID and invoked the $find('behavorID').add_valueChanged function within the $document.Ready. Everything seemed to be working fine until I encountered an issue where ...

What is the most effective way to programmatically select checkboxes based on array values in

Trying to keep it concise :) Working on a project that generates multiple pages of thumbnail images with checkboxes. The total thumbnails vary and are sorted into 1000 item html pages, called by a parent html page via iframe. Goal is for users to check che ...

What is the relationship between three.js transforms and CSS3 3D-transforms?

I am developing a unique open-source tool for exploring and visualizing the complexities of human anatomy. At the center of this tool is a dynamic 'chessboard' that occupies the majority of the screen. As you drag the board, various CSS3 3D-tran ...

Having trouble with setting up ENV variables while deploying the app on Heroku

I recently deployed my node.js app to Heroku, and I'm facing some issues with its functionality. The app loads fine, but when I try to sign in, it breaks down. It seems like the environment variables are not loading correctly, specifically the db vari ...

The dependability of the onbeforeunload function

Is the event window.onbeforeunload considered reliable? Does it trigger in all popular browsers? Will it still trigger if the client browser crashes? Can it effectively postpone the close event if more time is needed, or does it get interrupted? Are the ...

What is the method to track the number of tspan elements within each span element?

How can I use jQuery to count the tspan elements inside multiple span elements within svg text? var count_tspan = jQuery('span text').children().length; // 4 console.log(count_tspan); <div class="content-inner"> <span id="item-0" cl ...

What is the best way to replicate the functionality of AngularJS decorators in pure vanilla JavaScript (ES6)?

Using AngularJs Decorators offers a convenient method to enhance functions in services without altering the original service. How can a similar approach be implemented with javascript classes? In my current project, I have two libraries - one containing g ...

Cookie-setting isn't functioning properly on Opera and Firefox browsers, but it is working correctly on Postman when using Express

After spending an entire day researching, I have yet to find a solution to my problem despite trying everything possible. I suspect that the issue lies with the browser's security policy because my server and client are both running on different loca ...

Ways to connect a click event to a dynamically generated child element with the help of jQuery?

I am aware that similar questions have been asked elsewhere, but as someone new to jQuery, I am still struggling to attach a click listener to an a element within a dynamically appended ul.li.a structure in the DOM. Below is an example of how the structure ...

Ways to maintain a C# list on my webpage in order to modify it on the client side

Currently working with ASP.Net MVC 3.0 and facing an issue. My model contains a telephone list that I need to preserve for later manipulation and display using jQuery in my script. I attempted to save the list in a hidden field but have been unsuccessful ...

Is there a way to store the URLs that a user visits locally with a Chrome extension using JavaScript?

I am working on a Chrome extension that will save the URL link of the active tab when a user clicks on the extension icon. The goal is to store this URL in local storage and keep it saved until the active window is closed. I have set up an array called tab ...

Assessing an angular equation enclosed in quotation marks in HTML

There was a situation where I encountered the need to assess an angular expression enclosed in quotes, as shown below <a href="mailto:{{account["email"]}}" However, the mentioned approach does not effectively evaluate the content within nested quotes ...

The function fails to execute on the initial attempt

Currently, I am utilizing Kendo controls, specifically focusing on the Grid and Drop Down Lists. Since the Kendo Grid components do not come with a built-in handler for double click events, I have implemented some JQuery code to work around this limitatio ...