Tips for effectively utilizing the Angular ngIf directive for toggling the visibility of elements

<div *ngFor = "let element of myElements, let i=index" [ngClass]="{'selected':element[i] == i}">
    <li> Name: {{element.element.name}}</li>
    <li> Description: {{element.element.description}}</li>

    <select class="custom-select"> 
        <option *ngFor =" let soldier of mySoldiers"> {{soldier.soldier.name}}</option>
    </select>
    <button ></button>
</div>

I am using an ngFor directive to iterate through the elements in my database. Within that div, I also display a button and a select field, but I only want them to appear when the element is selected. If element 1 is selected, then the button and select will be displayed for that element, while all others will not have a button or select shown.

I believe we can achieve this with a simple ngIf directive, but I'm having trouble figuring it out. Any assistance would be greatly appreciated.

Answer №1

Remember that an li element cannot be a direct child of a div element - only a ul element can be the direct parent of an li. The correct approach is to nest the content inside the repeating li and use an ng-container with an *ngIf directive to conditionally display the content if the item is selected.

I have considered your method for determining the selected item, but there are more efficient ways to achieve this.

Keep in mind that spans are inline-level elements, so you will need to style them properly for correct display and spacing. Using flex properties like setting display: flex on the li and justify-content: space-between can help separate out the spans effectively.

<ul class="meus-items-list">
  <li *ngFor = "let item of meusItems, let i=index" [ngClass]="{'selected':item[i] == i}">
     <span> Name: {{item.item.name}}</span>
     <span> Description: {{item.item.description}}</span>

     <ng-container *ngIf="item[i] == i">
      <select class="custom-select"> 
       <option *ngFor =" let soldier of mySoldiers"> {{soldier.soldier.name}}</option>
      </select>
     <button >Click me</button>
     </ng-container>
  </li>
</ul>

You could also achieve this by nesting a ul / li inside the main li:

<ul class="my-items-list">
  <li *ngFor = "let item of myItems, let i=index" [ngClass]="{'selected':item[i] == i}">
   <ul>
     <li> Name: {{item.item.name}}</li>
     <li> Description: {{item.item.description}}</li>

     <li *ngIf="item[i] == i">
      <select class="custom-select"> 
       <option *ngFor =" let soldier of mySoldiers"> {{soldier.soldier.name}}</option>
      </select>
     <button >Click me</button>
     </li>
    </ul>
  </li>
</ul>

An alternative approach would be using CSS alone - applying display none to the select and button elements in all li's except for the selected one. While this keeps these elements in the DOM, it may not be the ideal method.

li:not(.selected) select,
li:not(.selected) button {
   display: none;
}

Answer №2

Consider this example showcasing a sample code snippet :

HTML :

<div *ngIf="displayed" class="success-msg alert box" role="alert">
        <strong>List Saved!</strong> Your changes have been successfully saved.
</div>

TS :

export class AppComponent implements OnInit{

  (...)
  public displayed = false;
  (...)

  saveTodos(): void {
   //show success message
   this.displayed = true;
   //wait for 3 seconds and hide
   setTimeout(function() {
       this.displayed = false;
       console.log(this.displayed);
   }.bind(this), 3000);
  }
}

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

Effortlessly retrieving the id attribute from an HTML tag using jQuery

Currently, I am encountering an issue with a code snippet that is designed to extract the value from an HTML tag. While it successfully retrieves a single word like 'desk', it fails when attempting to do so for an ID consisting of two or more wor ...

How do you incorporate ScrollTop animations using @angular/animations?

I'm attempting to recreate the animation showcased on Material.io: https://i.stack.imgur.com/OUTdL.gif It's relatively easy to animate just the height when clicking on the first card in the example above. The challenge arises when you click on ...

A Unique Identifier in Kotlin

In my typescript class, I have a member that accepts any as the name: interface ControlTagType { type?: String | null; [name: string]: any } class ControlTag { tagSource: String | null = null; tag: ControlTagType | null = null; } expor ...

Tips for aligning column components in a vertical position

My task is to align vertically the elements within multiple columns that include a headline, a description, and a button. By default, each element expands based on its content size https://i.stack.imgur.com/RJJP4.png However, I need all elements to be al ...

Managing relationships within TypeORM's single table inheritance using a base class for targeting relations

In my application, I aim to provide users with notifications in the form of news items of various types. The relationship between User and NewsItem needs to be one-to-many, with NewsItem serving as a base class for different types of news items. Below is ...

Using Javascript to choose an option from a dropdown menu

const salesRepSelect = document.querySelector('select[name^="salesrep"]'); for (let option of salesRepSelect.options) { if (option.value === 'Bruce Jones') { option.selected = true; break; } } Can someone please ...

Pixijs is unable to load spritesheets correctly

I am currently facing an issue while trying to load a spritesheet in PixiJS following the instructions provided on Below is the code snippet I am using: PIXI.Loader.shared.add('sheet', require('../assets/spritesheet.json')).load(sprite ...

Tips for choosing elements in jQuery that do not contain a particular element

How can I target elements in jQuery that do not contain a specific element within them? I am trying to create a sidebar that will close when the user clicks either the menu or the sidebar itself, excluding dropdown menus. Below is the structure of the menu ...

Ways to retrieve the quantity of a particular value within an object using TypeScript

I'm inquiring about how to retrieve the number of a specific value within an object using TypeScript. Here is the structure of the object: obj : TestObject = { name: "test", street: "test" subobj1: { status: warning, time: ...

Guide on receiving error responses in Angular when making API calls

While testing the API with incorrect credentials in Postman, an error response is received. However, when the same API is called from Angular, a different error status is returned. login(loginFormData){ this.service.login(loginFormData.value.username ...

Is annotation functionality available in version 3 of Chart.js?

In the previous version 2 of the chart, I utilized 'annotation' within options. However, after upgrading to version 3, it seems to have stopped working and I am unable to locate any information about this in the documentation. The following code ...

Exploring Mixed Type Arrays Initialization in Typescript using Class-Transformer Library

In my class, I have a property member that is of type array. Each item in the array can be of various types such as MetaViewDatalinked or MetaViewContainer, as shown below class MetaViewContainer{ children: (MetaViewDatalinked | MetaViewContainer)[]; ...

Modify the CSS of the gauge element without causing any issues

I am facing an issue while trying to resize this gauge element. Whenever I attempt to modify the container class to make it smaller, the entire gauge ends up distorting. Changing the position to relative seems to cause glitches at the edge of the gauge. An ...

Creating a model and assigning values in TypeScript

I am currently developing an angular application and need to send data to a post API. The JSON structure I am working with is as follows: { "name": "julie", "id": 1, "PersonalDetails": { "hom ...

I am looking to bring in just the tables from a different html/php page

I am currently working on a webpage that includes a php library, header, and other elements. I only need to import specific tables and information from this page onto another screen display, with the tables arranged side by side instead of vertically. My ...

Angular2 - Transmitting validation information from parent component to child component input validation

I am currently developing an automatic word correction module using Angular2. Within my child component, I have set up an EventEmitter. import {Component, Input, Output, EventEmitter} from '@angular/core'; ... export class StudyThumbsComponent{ ...

Python code encountered an issue while trying to find the element with the locator //input[@name="session[username_or_email]". The element could not

I have recently started learning about selenium and web scraping in general, and today I attempted to follow a tutorial on selenium that included the following command: from selenium import webdriver driver = webdriver.Firefox() driver.get("https://t ...

Exploring the HTML5 File API: Features and Capabilities

After looking into the File API, I'm curious about when all major browsers will fully support it: Firefox has supported it since version 3.6 Chrome since version 8.0 What about Opera and IE? Is the File API meant to replace flash-based uploaders li ...

Encountering unexpected behavior with the .data() method

I'm encountering an issue with my code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv= ...

Avoiding the restriction of narrowing generic types when employing literals with currying in TypeScript

Trying to design types for Sanctuary (js library focused on functional programming) has posed a challenge. The goal is to define an Ord type that represents any value with a natural order. In essence, an Ord can be: A built-in primitive type: number, str ...