Ways to display Div contents based on selected options in an Angular 2/4 list

"Struggling with dynamically displaying div contents" Situation:- I have a list of 3 items: *Menu1 *Menu2 *Menu3 and I have separate div contents for each of these menu items.

Requirement :- By default, Menu1 should be displayed. When Menu2 is clicked, the content of Menu1 and Menu3 should be hidden, and Menu2 content should be displayed.

How can I achieve this in Angular 2?

Here is my sample code and plunker:

home.component.html

<div class="item-list>
 <div><li (click)="Menu2==false && Menu3==false;">Menu1</li></div>
 <div><li (click)="Menu1==false && Menu3==false;">Menu2</li></iv>
 <div><li (click)="Menu2==false && Menu1==false;">Menu3</li></div>
<div>

<div class="information">
 <div *ngIf="Menu1==true && Menu2==false && Menu3==false  ">Menu1 contents goes here</div>
 <div *ngIf="Menu2==true && Menu1==false && Menu3==false ">Menu2 contents goes here</div>
 <div *ngIf="Menu3==true  && Menu2==false && Menu1==false ">Menu3 contents goes here</div>
</div>

home.ts

export class HomePage {


  private Menu1:boolean=true;
  private Menu2:boolean=false;
  private Menu3:boolean=false;
}

View plunker

Answer №1

Take a look at this solution:

Component:

import { Component } from 'angular2/core';

@Component({
  // Define the tag name in index.html to which the component is attached
  selector: 'hello-world',

  // Location of the template file for this component
  templateUrl: 'src/hello_world.html'
})

export class HelloWorld {
  private home: boolean = true;
  private about: boolean = false;
  private contact: boolean = false;

  showMenu(menuName: string) {
    let menus = ['home', 'about', 'contact'];
    menus.splice(menus.indexOf(menuName), 1);
    for (const menu of menus) {
      this[menu] = false;
    };
    this[menuName] = true;
  }
}

Template:

<div class="item-list">
    <div>
        <li (click)="showMenu('home')">home</li>
    </div>
    <div>
        <li (click)="showMenu('about')">about</li>
    </div>
    <div>
        <li (click)="showMenu('contact')">contact</li>
    </div>
</div>

<div class="information">
    <div *ngIf="home">home</div>
    <div *ngIf="about">about</div>
    <div *ngIf="contact">contact</div>
</div>

Answer №2

It appears that the initial list serves as the menu selector.

When you use (click)="Menu2==false", you are making a comparison, not assigning a value to Menu2.

To achieve the desired outcome, you can use the following code:

<ul>
  <li (click)="Menu2=false; Menu3=false; Menu1=true">Menu1</li>
  <li (click)="Menu1=false; Menu3=false; Menu2=true">Menu2</li>
  <li (click)="Menu2=false; Menu1=false; Menu3=true">Menu3</li>
</ul>

<div *ngIf="Menu1 && !Menu2 && !Menu3">1</div>
<div *ngIf="Menu2 && !Menu1 && !Menu3">2</div>
<div *ngIf="Menu3 && !Menu1 && !Menu2">3</div>

Additionally, it seems unnecessary to have 'divs' surrounding your LI elements.

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

Adding options to a select element using JavaScript dynamically

Is there a way to create a dynamic select list for year values using JavaScript? <form action="something"> some other fields <select id="year"> </select> </form> ...

Ways to include additional details in each row of an autocomplete feature

I have successfully implemented autocomplete for venues worldwide, but now I want to display the address of each venue below its name. For example, if the autocomplete suggests the venue name as ABCD, I want the address of that venue to appear right benea ...

Unsuccessful outcome from using a basic Ajax call alongside a result handler

Here is the JavaScript code: <script> jQuery(document).ready(function(){ // ensure DOM is ready jQuery('#veranstort').change(function(){ // trigger when input changes origin = "55767 Schwollen"; destination = "13509 Be ...

What are the best strategies for enhancing the performance of the jQuery tag:contains() selector

My goal is to extract all elements from a webpage that contain a specific set of words. For example, if I have an array of random words: words = ["sky", "element", "dry", "smooth", "java", "running", "illness", "lake", "soothing", "cardio", "gymnastic"] ...

Showing a loading overlay during an AJAX call on a JSP page

Hello there! I'm interested in adding a special effect to my JSP page's center when making an ajax call to load a dropdown menu. Can anyone help me with this? Thanks! ...

Navigating the world of Angular 5: Essential resources for beginners

My work requires me to learn Angular 5, although Angular 7 is currently the latest version. It seems like Angular 5 may be on its way out and online resources are becoming outdated. Can anyone suggest the best and most up-to-date resources for learning Ang ...

Add an image to a directory with Angular 7

I am having trouble uploading an Image to the assets/ folder using Angular 7. Below is my attempted solution: HTML: <form [formGroup]="form" (ngSubmit)="postData()" class="intro-form-css"> <div class="form-row"> ...

Troubleshooting a deletion request in Angular Http that is returning undefined within the MEAN stack

I need to remove the refresh token from the server when the user logs out. auth.service.ts deleteToken(refreshToken:any){ return this.http.delete(`${environment.baseUrl}/logout`, refreshToken).toPromise() } header.component.ts refreshToken = localS ...

Switching between different months in the React-Calendar display

I've been working with React-Calendar and I'm facing an issue where the month doesn't change when clicking the navigation arrows in the calendar. Here's a snippet of my code: ... const onActiveStartDateChangeHandler = ({ activeStartDa ...

The Div element on my webpage is not adjusting properly to fit the size of mobile devices

My app was created using Quick flip 2, and I needed to resize it for mobile screens, so I implemented jquery-mobile. Here is the code snippet: <!--css--> <style> .quickFlip, .quickFlip3 { height: 350px; width: 400px; } .quickFlip2 { ...

Using VueJS to dynamically manipulate URL parameters with v-model

Hello, I am new to coding. I am working on calling an API where I need to adjust parts of the querystring for different results. To explain briefly: <template> <div> <input type="text" v-model="param" /> ...

Developing step code for CucumberJS Scenario Outlines

In my feature file, I have the following scenario outlined for testing colors: Feature: Color feature @test Scenario Outline: Test color Given the first color is <COLOR_ONE> And the second color is <COLOR_TWO> ...

Conceal Navigation Panel while Scrolling Down, Reveal when Scrolling Up, Compatible with Chrome, Incompatible with Safari (on smartphones

I have implemented a code to hide my navbar when scrolling down and show it when scrolling up. This code works perfectly on desktop and in all browsers, including Chrome on mobile (iPhone). However, in Safari, the navbar sometimes shows, hides, and shows a ...

A guide on updating the Date Textfield value in Material UI

In my data structure, I have an array of objects with unique ids and date values. For instance, the array named stepDates might appear like this: [ { id: 1, date: "2021-07-23" }, { id: 2, date: null }, { id: 3, d ...

"Utilizing Vue.js to determine whether a checkbox is filled with data or left

My goal is to create a checkbox using vue js without writing a method. I want the checkbox to default to false, and when checked, I want the data "opening_balance" to be an empty array. Conversely, if the checkbox is unchecked, I want it to be omitted when ...

How to implement debouncing for an asynchronous custom validator in Vue.js using vuelidate?

I encountered an issue with my validator function that checks if a username is already registered in the database. The problem was that the request was being sent to the server after every single character input, which was far too frequent. To remedy this, ...

Generate a collection of elements using a different collection as a reference

I am struggling with an array of objects: let data = [{ createdDate: "2222", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c3d487c6d7b7c266b6765">[email protected]</a>", histories: [ ...

I have come to realize that my understanding of how Sass nesting works was misguided

Currently struggling with understanding Sass nesting. Any explanations on where I went wrong would be greatly appreciated, as this is a beginner-level issue for me. Thank you in advance. .header { display: flex; height: 10vh; background-color: #13192 ...

Elevate a div over another div

I have a situation where I need to nest two divs inside another div with the ID "video-wrapper". Here is the HTML code: <div class="row"> <div class="video-wrapper col-lg-2"> <div class="video-thumbnail"> <img ...

Trouble with React Native ListView Item Visibility

I'm currently working on integrating the React Native <ListView /> component with the <List /> and <ListItem /> components from React Native Elements. However, I seem to be facing an issue where the <ListItem /> component is no ...