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

overlay appears as I reveal the slide-out menu

Struggling with adding an overlay to an expanding navigation bar, similar to Youtube's overlay when the slide-out nav is open. Need help with the implementation. Here is the javascript code for the expanding navigation using jQuery: 'use strict ...

"Wordpress Pluto theme: A stellar choice for your

I'm trying to add a link in my main template.index file that will redirect to one of my pages when clicked on the JavaScript button at the top in Pluto theme. Currently, the text is there but clicking on it opens something I don't want. Here&apo ...

The vue template is indicating an error related to unused variables according to the eslint rule vue/no

Perhaps this information will come in handy for someone. I am working with a Vue template that contains HTML. <template slot="HEAD_Status" slot-scope="data"> <!-- some html without using of data --> </template> Eslint is showing [v ...

The ::before pseudo element is malfunctioning when used in the makeStyles function

I am currently utilizing the makeStyles function in React, but I seem to be facing an issue where the content within the ::before pseudo-element is not displaying. Strangely enough, when the content is an image it works fine, but text does not render. Jus ...

An Angular module downloaded from npm seems to be lacking the required @NgModule declaration

There seems to be a missing @NgModule and @Directive declarations in an NPM module, even though they exist in the source code on Github. This is causing an issue with importing a directive for databinding from an HTML attribute. I am attempting to utilize ...

Having trouble with transferring information from JQuery to PHP

Currently, I'm working on transmitting data from jQuery to PHP. Here's an excerpt of what I've done: var jsonArray = JSON.stringify(dataArray); $.ajax({ type: "POST", url: "addcar_details.php", ...

Is there a way to arrange the outcomes in a single line?

I need help displaying my results in three rows side by side in React/JavaScript using flexbox. Since I only have one CardItem, I can't just copy and paste it three times as it would show the same result in each row. Is there a way to achieve this wit ...

Tips for inserting a line break within the output of an Angular pipe

Is there a way to display dates on separate lines in an Angular pipe? <th>{{(date | date: 'EEE MMM d')}}</th> Currently, the output is displayed like Mon Jul 20 - all in the same line. But I want it to be displayed like: Mon Jul ...

What is the process for changing a field in a document on firestore?

Is there a way to modify a specific field in a firestore document without retrieving the entire document beforehand? ...

Using Typescript to resolve a package from a location other than the default node_modules directory

I am currently delving into typescript and eager to start dabbling in creating packages. Here is the current layout of my project: myProject/ ├── node_modules/ ├── src/ │ ├── app │ ├── index.ts │ ├── packages ...

Issue with border styling in Material-UI vertical ToggleButtonGroup

In my current front-end project, I have implemented the React Material UI ToggleButtonGroup. For a Multiple Selection example with vertical styling, you can refer to this code snippet: https://codesandbox.io/s/eyk66?file=/demo.js However, I encountered a ...

Unable to subscribe to mergeMap observable in Angular 13

I am currently working on implementing a connection scenario in Angular that is based on user roles. When the user clicks on the "CONNEXION" button after filling out the form with their username and password, two API URLs are triggered to facilitate the sa ...

Enhance the dimensions of images on Tumblr

Is there a way to customize the width of a photo in HTML? I am having trouble changing the size of a photo set on Tumblr to be larger. I have tried researching it, but I don't understand where to place maxwidth:600px or if this is even the correct app ...

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

What is the best way to create a flexible Ul-LI menu?

Is it possible to create a flexible menu where clicking on an item does not cover other items in the menu? #demo { margin: 30px 0 50px 0; font-family: sans-serif; } #demo .wrapper { display: inline-block; width: 180px; height: 20px; position ...

Typegoose's representation of modifying data

Recently, I delved into the world of NestJS and kickstarted a sample project. To integrate MongoDB seamlessly, I opted for Typegoose. A useful online tutorial () caught my eye, illustrating how to employ abstractions with base typegoose models. Hence, my ...

Is it possible to use ng-bootstrap with vertical tabs?

I'm experimenting with displaying ng-Bootstrap tabs vertically, but the provided example doesn't quite fit my needs. I'm envisioning a layout similar to what I've sketched in the diagram. Do you think it's achievable? Any suggestio ...

After the form is submitted on the current page, it will not submit again using jquery unless I refresh the page

Currently, I am attempting to submit my form on the same page utilizing jquery. However, after the initial submission, any further attempts fail. It seems that in order for the submission to work properly again, I need to refresh the page first. What cou ...

The nested fields in PayloadCMS GraphQL are appearing as null

When using the PayloadCMS GraphQL plugin, I encountered an issue with the type: "relationship" fields always returning null, no matter what I tried. My goal is to create a simple blog without any complexities. Despite reaching out for help in the ...

"All my online spaces are chaotic and cluttered beyond belief, overflowing with content in high-definition

One issue that frequently arises for me when developing websites is related to media queries and resolution. I have utilized the following code using a max-width of 1920px: @media only screen and (max-width : 1920px) {} However, I am facing challenges in ...