Ways to dynamically display or hide content in Angular 7

>when an English button is clicked, its corresponding div should be shown. If another button is clicked, its div should also show without closing the previous one. I want each div to close only when its respective button is clicked again.
>Please note that this needs to be done dynamically as the number of languages is unknown.
>Ensure that it is not hardcoded for static data.

*in my HTML *

 <div *ngFor="let lang of langList;let index = index" >
          <div class="engbutton">
              <button class="englishButton" (click)="onclickEnglishDiv(lang,index)">{{ lang }}</button>
              <div *ngIf="visibleIndex === index" class="knowEnglish">
                <div>
                  <div *ngFor="let data of filteredLangList" class="engDivObj">{{data.name}}</div>
                </div>
              </div>
            </div>
      </div>

in my TS

 onclickEnglishDiv(clickLang,index){  
    if (this.visibleIndex !== index) {
      this.visibleIndex = index;
    }     
  }
  • Clicking on a div will open it, and clicking on another div will close the previous one while opening the new one. * What I want *
I want each button to open its respective div without closing any other divs. Only when the same button is clicked can its div be closed.
- Make it dynamic so it works smoothly even with new data.

View the sample here

Check out the jQuery versionhere. I need the same functionality in Angular 7 with a dynamic approach, no hardcoded boolean values for each div.

Answer №1

One way to address this issue could be by storing visible indices instead of just a single index, for example:

<div class="box">
  <div class="container">
      <div *ngFor="let lang of langList;let index = index" >
          <div class="engbutton">
              <button class="englishButton" (click)="onclickEnglishDiv(lang, index)">{{ lang }}</button>
              <div *ngIf="visibleIndices.has(index)" class="knowEnglish">
                <div>
                  <div *ngFor="let data of studentList | filterLanguages:lang" class="engDivObj">{{data.name}}</div>
                </div>
              </div>
          </div>
      </div>
  </div>
</div>
...
export class ShoHideComponent implements OnInit {
  visibleIndices = new Set<number>();

  ...

  onclickEnglishDiv(clickLang, index): void {
    if (!this.visibleIndices.delete(index)) {
      this.visibleIndices.add(index);
    }
  }
}

It's worth noting that the logic for filtering languages has been moved to the filterLanguages pipe in order to ensure each element displays its own unique set of filtered languages. Here is a link to an example on StackBlitz.


Another approach could involve creating a separate component for the button as shown below:

<!-- sho-hide.component.html -->
<div class="box">
  <div class="container">
      <div *ngFor="let lang of langList;let index = index" >
          <app-lng-button [lang]="lang" [languages]="studentList | filterLanguages:lang"></app-lng-button>
      </div>
  </div>
</div>
// lng-button.component.ts
@Component({
  selector: 'app-lng-button',
  templateUrl: './lng-button.component.html'
})
export class LngButtonComponent {
  @Input()
  lang!: string;

  @Input()
  languages: string[] = []

  open = false;
}
<!-- lng-button.component.html -->
<div class="engbutton">
  <button class="englishButton" (click)="open = !open">{{ lang }}</button>
  <div *ngIf="open" class="knowEnglish">
    <div>
      <div *ngFor="let data of languages" class="engDivObj">{{data.name}}</div>
    </div>
  </div>
</div>

Check out this StackBlitz link for a live demonstration.

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

Utilize Office Scripts to update values across numerous worksheets

Looking for ways to improve the performance of this script, as it currently takes 45 seconds to run. Any ideas? function main(workbook: ExcelScript.Workbook) { try { const sheets = workbook.getWorksheets(); for (let sheet of sheets) { const break ...

Error encountered during npm installation - EPERM: Operation not allowed

Today's challenge began when attempting to run the angular4 project and encountering this error: npm install eperm operation not permitted. In an effort to resolve it, I decided to delete the node modules folder and try again. However, upon running np ...

What is the best way to transform an Observable array containing objects into an Observable that emits the data contained within those objects?

Encountering an error: Error: Type 'Observable<Country[]>' is not assignable to type 'Observable'. Type 'Country[]' is missing properties like name, tld, alpha2Code, alpha3Code and more.ts(2322 The issue might be due ...

Encountering a npm lifecycle error upon restarting

I recently started learning Angular 2 using Visual Studio Code as my IDE. Initially, everything worked fine when I executed "npm start" for the first time. However, I encountered an error when I tried to stop the process with CTRL+C and then re-executed "n ...

What could be causing Angular's Renderer2 to generate inaccurate outcomes?

Having an array of queries with varying positions of underscores: Newtons __________ Law dictates __________ is the result of an object's mass and speed. My goal is to show each question to users, replacing the blanks with in ...

"The functionality for detecting changes in an Electron application has ceased to work after implementing zone.js version 0.9.1

Recently, I took over an Electron app originally built with Angular 6 and decided to update it to Angular 8. After following all the upgrade guides, I managed to get everything up and running smoothly - or so I thought. It wasn't until I started inter ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

The system encountered an issue: unable to determine the property 'endsWith' of an undefined value

As I delve into writing my initial unit tests for the components, certain issues have arisen: TypeError: Cannot read property 'endsWith' of undefined. How can I define the data.iconPath in my test to resolve this error? Presenting my component ...

Error: No routes found in Angular 5

I have developed an Angular 5 app and set up the following routing configuration in app-routing.module.ts file: import { ControlPanelComponent } from './dashboard/control-panel/control-panel.component'; import { MainComponent } from './dash ...

Can Angular's change detection be triggered by a change in @Input?

As of now, I am immersing myself in guides and tutorials on Angular's change detection. There are some statements that are quite perplexing to me. Therefore, I am seeking confirmation or clarification. The default Change Detection is activated "every ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

Using ngx-bootstrap typeahead with custom itemTemplate for objects

I've created a custom ngx-bootstrap/typeahead component for my ngx-formly generated forms. This component fetches search results from an API and is designed to be reusable for various objects, making it dynamic. My goal is to have the typeahead retri ...

Have there been any instances of combining AngularJS, ASP.NET-WebApi, OData, Breeze.js, and Typescript?

I am attempting to combine different technologies, but I am facing challenges as the entity framework meta-datas are not being consumed properly by breeze.js. Despite setting up all configurations, it's proving to be a bit tricky since there are no ex ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

Angular6 returns the result after subscribing to an HTTP POST request

Currently, I am in the process of learning angular and attempting to create a component that allows users to register through my web API. Within my component, the code on form submission looks like this: onSubmit(contactFormRef: NgForm) { const resu ...

Is there a way to convert a JavaScript object to a class while eliminating unnecessary properties?

In my current project, I am using Typescript with ExpressJS to build APIs. Let's say I have a typescript User model defined as follows: class UserModel { id: number; email: string; password: string; name: string; dob: Date; ge ...

Combining multiple Observables and storing them in an array using TypeScript

I am working with two observables in my TypeScript code: The first observable is called ob_oj, and the second one is named ob_oj2. To combine these two observables, I use the following code: Observable.concat(ob_oj, ob_oj2).subscribe(res => { this.de ...

How to display a festive greeting on the specific holiday date using the ngx-bootstrap datepicker

Currently, I have implemented the ngx-bootstrap datepicker for managing appointment schedules. I have disabled weekend days and holiday dates, but now there is a requirement to display a tooltip with a holiday message when hovering over a holiday date. htt ...

Strategies for Creating a Test Suite for RepositoryFactory in Vue.js/Nuxt.js

Summary of RepositoryFactory Implementation An implementation of the RepositoryFactory pattern has been carried out for API connection in a Vue.js/Nuxt.js application. For more details, refer to this article: here hogeRepository.ts import { NuxtAxiosInst ...

What is the best way to configure an EmailId validator in Angular 6 to be case insensitive?

My register and login page include a form validator pattern matching for the registration form. this.registerForm = this.formBuilder.group({ firstName: ['', Validators.required], emailId: ['', [Validators.required, Validators.patt ...