Toggle visibility of content with the click of a button

Hey there, fellow coder!

I'm still getting the hang of Angular 2 and Typescript, so please be patient with me as I learn.

I am working on a project where I have 5 buttons that should toggle the visibility of content, similar to a side menu. Below is the code snippet for this functionality:

HTML - Code

  <li class="navigation-items"> 
    <button class="dropdown-header" (click)="onSelect(2)">Link 2</button> 
    <div *ngIf="DropdownVar == 2" class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>

Typescript - Code

DropdownVar = 0;

onSelect(x){
 this.DropdownVar = x;
 console.log(x);
}

Currently, it seems like my variable is getting updated correctly, but the *ngif directive is not working as expected. Are there better approaches to solve this issue?

Additionally, I would like to add some animations to the content that is being displayed. I believe CSS can help in achieving this effect.

Answer №1

You have the option to directly set (click)="DropdownVar=2" without utilizing the onSelect method.

<li class="navigation-items">
    <button class="dropdown-header" (click)="DropdownVar=2">Link 2</button>
    <div *ngIf="DropdownVar === 2" class="dropdown-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
    </div>
</li>

Remember to use === instead of == in Angular2,

Answer №2

To display or hide content dynamically, you can use the [hidden] attribute instead of ngIf directive.

<li class="navigation-items"> 
<button class="dropdown-header" (click)="onSelect()">Link 2</button> 
<div  class="dropdown-content" [hidden]="IsHidden">
  <a href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
</div>

Inside your component:

IsHidden= true;

onSelect(){
 this.IsHidden= !this.IsHidden;
}

Answer №3

Utilize [hidden] in place of ngIf for better performance

<li class="navigation-items"> 
    <button class="dropdown-header" (click)="onSelect()">Link 2</button> 
    <div  class="dropdown-content" [hidden]="IsHidden">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>

In Component

IsHidden= true;

onSelect(){
this.IsHidden=true;
 this.IsHidden= !this.IsHidden;
}

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

What is the best way to merge two observable sequences sequentially?

I currently have an Observable set up like this: this.data$ = this.dataService.toGetAllData(); If I subscribe to this Observable, it will return an array of objects like the following: this.dataService.toGetAllData().subscribe(response => console.log(r ...

Accessing a function from a separate module in Angular 2

I am encountering an error message stating "has no exported member test" when trying to import test from ConfigAppProviderModule. Could there be a mistake in how I am writing the service with config in the module? import { NgModule ,InjectionToken,Injec ...

leveraging office-ui-fabric in a dotnet core and react app

I am working on a dotnet core and react application and would like to incorporate the Office-ui-fabric library. package.json { "name": "app_fabric_test", "private": true, "version": "0.0.0", "devDependencies": { "@types/history": "4.6.0", ...

How can one retrieve the "code" attribute from a FirebaseError object in AngularFire using TypeScript?

When using FirebaseError with a "code" property, how can you access it within the catch method of a promise? The code snippet below results in a TypeScript error: Property 'code' does not exist on type 'Error'. this.af.database .object ...

Trouble accessing the Ionic SQLite database: Unable to open

I encountered some errors while attempting to connect my ionic app to a database. I am currently running the app on an android device using Google Chrome DevTools to troubleshoot the issue. Check out the createDatabase() function and the specific error th ...

Navigating Angular single page application routes within an ASP.NET Web API project

Developed an Angular single-page application with specific routes: /messages /messages/:id By using ng serve, I can navigate to these pages at URLs like localhost:4200/messages and localhost:4200/messages/:id After building the solution, I transferred t ...

Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server? ...

Modify typescript prior to typechecking

Consider the following TypeScript file: class A { private x? = 0; private y? = 0; f() { console.log(this.x, this.y); delete this.x; } } const a = new A(); a.f(); When building it in webpack using awesome-typescript-loader ...

When implementing Swiper in TypeScript, an error is encountered: TypeError - Attempting to invoke the Swiper class constructor without using the 'new' keyword

I am facing an issue for which I couldn't find a solution, so I'm attempting to solve it myself for the first time. I am using TypeScript and Next.js, but unfortunately, Swiper does not offer direct support for Next.js and TS. Below is the TypeS ...

The ng2-admin project is missing the `npm run build:prod:aot` script

When I use the command npm run build:prod to create the ng2-admin app image, everything works fine. However, when I deploy this image on Docker, it keeps throwing errors. In an attempt to troubleshoot, I decided to run: npm run build:prod:aot But runni ...

Tips for transferring information from a Sidemenu to a different page during navigation

Essentially, I have two types of users: Teachers and Students. How can I display different profile screens depending on the user type? The Sidemenu is located in app.components.ts file. ...

Function that sets object properties based on specified keys and verifies the value

Let's consider a scenario where we have an object structured like this: interface Test{ a: number; b: string; c: boolean; } const obj:Test = { a: 1, b: '1', c: true, } We aim to create a function that can modify the value ...

What is the best way to assign unique IDs to automatically generated buttons in Angular?

Displayed below is a snippet of source code from an IONIC page dedicated to shapes and their information. Each shape on the page has two buttons associated with it: shape-properties-button and material-information-button. Is it possible to assign different ...

Refresh the ngrx state data whenever the RouteGuard is triggered

When it comes to ensuring the protected view of an entity, I utilize a RouteGuard to pre-load the necessary data for the desired view into the ngrx store. However, as the corresponding data from the backend can be subject to change over time, it is crucial ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

"Uploading user profile images with Angular, Express, Multer, and Mongoose made easy

Hey there, I'm currently using multer to upload images. When I select an image, it gets saved in the backend folder called uploads. However, I would like to store it in a MongoDB database and then display that image on the frontend using Angular. I&ap ...

Ways to Halt observable.timer in Angular 2

As I work on Angular2's Component, I am currently implementing the following functions: export class MypageEditComponent { ngOnInit() { this.timer = Observable.timer(100, 100); this.timer.subscribe(t => { this.setFormData(); } ...

Can you demonstrate how to implement a useState hook as a prop in a component using TypeScript and React?

I have a pair of elements and Currently, I am passing a useState hook from Admin component to Login component as a setAuth prop In my Admin element: const Admin = () => { const [authState, setAuthState] = useState(false); <Login setAuth={set ...

Adjust the dimensions of the mat-icon-button

Is there a way to adjust the size of a mat-icon-button? Currently, my icon is set at 24px and I would like to increase it to 48px. I am using mat-icon as the button content, but it seems that mat-icon-button has a fixed size of 40px by 40px. <button ...

Is there a way to automatically close the previous accordion when scrolling to a new one on the page?

Currently, I am working with the material-ui accordion component and facing an issue where all accordions are initially opened. As I scroll down the page and reach a new accordion, I want the previous ones to automatically close. The problem arises when tr ...