Issue with Angular ngStyle toggle functionality not activating

I'm having an issue with toggling my navbar visibility on click of an image. It works the first time but not after that. Can anyone provide some assistance?

Link to Code

<img id="project-avatar" (click)="toggleNavbar()" width=20, height=20 style="position: relative;" alt="Show Hide Navigation Menu" src="/assets/img/slider_hide.png" />
<div> 

<div class="showHideNavbar" [ngStyle]="displayNavbar == '1' ? {'visibility': 'visible'} : {'visibility': 'hidden'}">
  <mat-toolbar color="primary" >

component.ts

displayNavbar: string;

ngOnInit() {
    this.displayNavbar = '1';
}

toggleNavbar() {

    if(this.displayNavbar == '0') {
        this.displayNavbar = '1';
        alert(this.displayNavbar);
    } if(this.displayNavbar == '1') {
    //    alert("1 - Changing to 0");
        this.displayNavbar = '0';
    } else {
        this.displayNavbar = '1';
    }
}

1) The toolbar should show on page load - it is showing as expected https://i.stack.imgur.com/RqjGS.png

2) Clicking the icon at the top left corner should hide the toolbar - working first time https://i.stack.imgur.com/RsamL.png

3) Clicking the icon again should display the toolbar - currently NOT working

Link to Code for Troubleshooting

Answer №1

update

 [ngStyle]="displayNavbar === '1' ? {'visibility': 'visible'} : {'visibility': 'hidden'}"

to

 [style.visibility]="{'visibility': displayNavbar === '1' ? 'visible' : 'hidden'}"

or

[style.visibility]="displayNavbar === '1' ? 'visible' : 'hidden'"

update toggleNavbar function to

toggleNavbar() {
   this.displayNavbar = (this.displayNavbar === '1') ? '0' : '1'
}

Link to StackBlitz Example

Answer №2

Instead of using 1 and 0 to toggle , try using true or false like the following approach, which can simplify the code and improve rendering speed.

Component.ts

 displayNavbar: boolean;ngOnInit() {
    this.displayNavbar = false; // set it to true or false based on the logic during initialization
}

toggleNavbar() {
this.displayNavbar = !this.displayNavbar; // dynamically toggles between true and false
}

html

  <img id="project-avatar" (click)="toggleNavbar()" width="20" height="20" style="position: relative;" alt="Show Hide Navigation Menu" src="/assets/img/slider_hide.png" />
<div> 

<div class="showHideNavbar" [ngStyle]="(displayNavbar) ? {'visibility': 'visible'} : {'visibility': 'hidden'}">

Answer №3

Incorporate a property into your TypeScript script to contain the logic as illustrated below:

get displayMenu(): boolean {
    return this.showingMenu === 1;
}

You can then utilize *ngIf with this property to toggle the visibility of an element.

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 purpose does the # symbol serve in Angular when interpolating values?

Here is an example provided from the following link: https://angular.io/guide/lifecycle-hooks export class PeekABoo implements OnInit { constructor(private logger: LoggerService) { } // Implementing OnInit's `ngOnInit` method ngOnInit() { this ...

Unsure how to proceed with resolving lint errors that are causing changes in the code

Updated. I made changes to the code but I am still encountering the following error: Error Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. It is recom ...

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

Perpetually launching "npm start" on the server

I have been attempting to deploy an angular2 test application on a server. It is functioning well on my local machine using the command NPM start as indicated in my package.json file: "start": "concurrent \"npm run tsc:w\" \"npm run lite&bs ...

What is the process for removing globally declared types in TypeScript definitions?

There are numerous libraries that cater to various platforms such as the web, Node servers, and mobile apps like React Native. This means they can be integrated using <script /> tags, require() calls, or the modern import keyword, particularly with t ...

The video element in my Angular application is not functioning properly in Safari

I am having an issue with playing a video in my angular app. It works perfectly in all browsers except for Safari : <video controls autoplay muted class="media"> <source src="https://my-site/files/video.mp4" type="video/mp4" /> </video& ...

Tips for troubleshooting compile errors when updating an Angular project from version 6 to 7

I am currently working on upgrading my Angular 6 project to Angular 10, following the recommended approach of going through one major version at a time. Right now, I am in the process of updating it to version 7.3. Despite following the steps provided on u ...

Running cypress tests with regression or smoke tags within nx workspace is a straightforward process

I have a cypress project set up and I am trying to run cypress tests based on tags using the nx command. cypress grep--->"@cypress/grep": "^4.0.1" After applying the nx command like this: nx run e2e:e2e --tags=@regression The issu ...

What is the best way to remove all attributes from one interface when comparing to another?

Consider the following two interfaces: interface A { a: number; b: string; } interface B { b: string; } I am interested in creating a new type that includes all the keys from interface A, but excludes any keys that are also present in interface B. ...

What is the best method for inserting a 'Placeholder' in an Angular datePicker?

Looking for assistance with placing placeholder text inside an Angular datePicker, specifically wanting to display 'From' and 'To' labels within the datePicker. datePicker I am a novice when it comes to Angular development - can someon ...

Encountering error 2307 "Cannot find module" when using Vue 3 with script setup and TypeScript

I am currently attempting to run unit tests in my Vue3 project using vue/test-utils and jest. Upon running the npm run test script, the test fails due to an error with the import: error TS2307: Cannot find module 'pathtofile/file.vue' I have tr ...

Error: Vercel deployment of Next.Js app fails due to undefined localStorage

Encountering the issue ReferenceError: localStorage is not defined when attempting to deploy my Next.JS app on Vercel. const NewReserve: React.FC = () => { const setValue = (key: string, value: string) => { return localStorage.setItem(key, val ...

Could Typescript decorators be used as mixins?

In the process of developing a complex Angular2 application, I have created a base class that serves as the foundation for my components: export abstract class ReactiveComponent implements OnInit, OnDestroy, AfterViewInit { abstract ngOnInit(): void; ...

What is the best way to initiate a dialog within the handleSubmit function?

In my project, I have a component called SimpleDialog which is defined in the File.tsx file. export default function SimpleDialog() { const handleSubmit = (event: any) => { <SimpleDialog />; } return( <form> <Button type="submit& ...

Unrestricted Angular Audio Playback without CORS Restrictions

I am currently developing a web application using Angular4 that will include the feature of playing audio files. Unfortunately, I am facing an issue where I do not have control over the server serving the media files, and therefore cannot make any modifica ...

Is there a way to combine compiling TypeScript and running the resulting .js file into one build command in Sublime Text 3?

I have successfully installed the TypeScript plugin on Sublime Text 3. Once installed, a build system is added to the menu for easy access. https://i.stack.imgur.com/m21bT.png You can simply press "Command + B" to build a .ts file. My goal is to compile ...

Issue with Component in Angular not functioning properly with proxy construct trap

Currently working with Angular 17, I have a straightforward decorator that wraps the target with Proxy and a basic Angular component: function proxyDecorator(target: any) { return new Proxy(target, { construct(target: any, argArray: any[], newTarget: ...

Creating an internal link to navigate to a specific element ID within another Angular component

Seeking Solution I am facing a challenge in using an internal link within the <a> tag to navigate to a specific section of another component by HTML ID. My Exploration First, I visited this site: https://www.w3schools.com/html/html_links.asp bu ...

Struggling with TypeScript and JsObservable? Let us assist you!

Having previous experience with JSRender, JSViews, and JSObservables, I recently embarked on a new project using TypeScript. Unfortunately, I am struggling to understand how to properly utilize TypeScript in my project, especially when it comes to referenc ...

Exploring the terrain of observable data

Understanding how to filter an observable is really challenging for me right now. I have a gadget {name: string, description: string} I possess an observable collection of gadgets [{},{},{}] My goal is to iterate through my observable collection of ga ...