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

When the React Native Expo app is running, the TextInput form is covered by the keyboard

When I launch the app using expo and implement my DateFormInput component, the issue of Keyboard covering TextInput arises. Despite trying packages like "@pietile-native-kit/keyboard-aware-scrollview", "@types/react-native-keyboard-spacer", "react-native-k ...

Adding JavaScript files to a project in Ionic2 with Angular2 integration

I'm looking to incorporate jQuery into my Ionic2 app, which requires loading several JavaScript files: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/j ...

What strategies can be employed to create a system for managing multiple permission groups in MongoDB effectively?

Currently, I am tackling a complex project management application which involves the challenge of setting up resource permissions for various user profiles. The task at hand: User scenario Meet John, a user with a standard user profile. John initiates a ...

The serverTimeStamp() function in firebase.firestore.FieldValue does not allow for the Timestamp data type to be used

async addNewUser(id: string, email: string) { await this.afs.doc<MemberProfileModel>(FirestoreDbConstant.MEMBER_PROFILES + `/${id}`).set({ email, registeredDate: firebase.firestore.FieldValue.serverTimestamp(), }); } This appro ...

What is the most efficient way to perform an inline property check and return a boolean value

Can someone help me with optimizing my TypeScript code for a function I have? function test(obj?: { someProperty: string}) { return obj && obj.someProperty; } Although WebStorm indicates that the return value should be a boolean, the TypeScript compil ...

Toggle the visibility of the navigation bar in Angular based on the user

I have implemented rxjs BehaviorSubject in my login page to transmit data to auth.service.ts, enabling my app.component to access the data stored in auth.service.ts. However, I now require the app.component to detect any changes made to the data in auth.se ...

Mastering the art of styling with SASS

The introductory guide suggests: When it comes to integrating the Kendo UI theme into your project, there are numerous approaches available. One recommended method is utilizing Webpack along with its Sass loader, enabling the customization of the Kendo UI ...

Modification of encapsulated class in Angular is not permitted

Within Angular, a div element with the class "container" is automatically created and inserted into my component's HTML. Is there a way to modify this class to "container-fluid"? I understand that Angular utilizes encapsulation, but I am unsure of how ...

I need assistance with the following issue: the type 'Observable<ArrayBuffer>' cannot be assigned to the type 'Observable<User[]>. Can anyone provide a solution for this problem?

Encountered an issue with the error message: Type 'Observable' cannot be assigned to type 'Observable<User[]>' while working on setting up Angular service.ts for implementing HTTP requests. ...

Angular 2: Streamlining user interface connections with extensive data rows

My challenge lies in displaying a list of items stored in an array[] when the user clicks on a tab. The data set contains around 10k rows, which is quite large, and currently takes approximately 2 to 3 seconds to render on the UI after the click event. I a ...

amChartv5 on Angular is successfully displaying a Gantt chart that includes multiple categories with the same name being resolved

I've been working on integrating an amCharts v5 gantt chart with Angular 13. Each bar in the chart represents a project, and if there are multiple occurrences of a category, they should stack like a timeline. I've successfully retrieved data from ...

Placeholder variable not specified in radio buttons

I am currently facing challenges applying validations to radio buttons in Angular. Normally, I create a #templateRefVariable on the input for other input types, which allows me to access the NgControl and use properties like touched. My goal is to set the ...

"Trouble with Bootstrap Collapse function - Utilizing ng-bootstrap, eliminating the need for JQuery

In my Angular 8 project, I have Bootstrap 4.3.1 and ng-bootstrap 5.1.1 integrated. As per the ng-bootstrap documentation, including ng-bootstrap in your project eliminates the need to manually add jQuery, as it is encapsulated by ng-bootstrap and not requ ...

Steps for appending a string to a variable

Currently working on creating a price configurator for a new lighting system within homes using Angular 7. Instead of using TypeScript and sass, I'm coding it in plain JavaScript. Page 1: The user will choose between a new building or an existing one ...

Successful build of node app, however, not appearing on Heroku for MEAN Stack application

After numerous failed attempts, I finally managed to successfully build and deploy my app on Heroku. However, when I tried to access it, all I got was an 'Application error'. The log for the successful build is as follows: -----> Node.js app d ...

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

Utilizing Angular's Mat-Table feature to dynamically generate columns and populate data in a horizontal manner

I am in need of a solution where I must populate the mat-table in a horizontal format with an array of JSON objects. The input array is as follows: [{ "SAMPLERULEID": 69, "SAMPLERULENAME": "Sample1", &q ...

To populate an Ionic list with items, push strings into the list using the InfiniteScroll feature

Looking for help with implementing infinite scroll in a list? I am using the ion-infinite-scroll directive but struggling to push string values into my list. The list contains names of students in a classroom. Can anyone provide guidance on how to push str ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

Obtaining the value of an ion-toggle in Ionic2 using the ionChange

Below is the toggle I am referring to: <ion-toggle (ionChange)="notify(value)"></ion-toggle> I am looking for a way to retrieve the value of the toggle when it is clicked in order to pass it as a parameter to the notify method. Any suggestion ...