Applying ngClass and onClick to a Div Element is Not Working

I am currently working on converting a JavaScript project into Angular. However, I am facing difficulty understanding why some classes are causing the menu to disappear, even after reviewing the documentation multiple times. My goal is to have the menu rotate into an X shape only when the .menu-btn is clicked on.

Below is the JavaScript code that I'm attempting to convert:

// Select DOM Items
const menuBtn = document.querySelector(".menu-btn");
const menu = document.querySelector(".menu");
const menuNav = document.querySelector(".menu-nav");
const menuBranding = document.querySelector(".menu-branding");
const navItems = document.querySelectorAll(".nav-item");

// Set Initial State Of Menu
let showMenu = false;

menuBtn.addEventListener("click", toggleMenu);

function toggleMenu() {
if (!showMenu) {
menuBtn.classList.add("close");
menu.classList.add("show");
menuNav.classList.add("show");
menuBranding.classList.add("show");
navItems.forEach((item) => item.classList.add("show"));

// Set Menu State
showMenu = true;
} else {
menuBtn.classList.remove("close");
menu.classList.remove("show");
menuNav.classList.remove("show");
menuBranding.classList.remove("show");
navItems.forEach((item) => item.classList.remove("show"));

// Set Menu State
showMenu = false;
}
}

app.component.html

<header>
<div class="container">

    <div class="menu-btn" [class.menu-btn.close]="check" (click)="myfunction()">
        <div class="btn-line"></div>
        <div class="btn-line"></div>
        <div class="btn-line"></div>
      </div>
      
      <!-- Overlay that comes up when you click menu -->

      <!-- Profile Image put in through CSS -->
      <nav class="menu" [class.menu-btn.show]="check" (click)="myfunction()">
        <div class="menu-branding" [class.menu-btn.show]="check" (click)="myfunction()">
            <div class="portrait"></div>
        </div>
       
        <!-- Pages -->
        <ul class="menu-nav" [class.menu-btn.show]="check" (click)="myfunction()">
            <li class="nav-item current" [class.menu-btn.show]="check" (click)="myfunction()">
                <a href="index.html" class="nav-link">Home</a>
            </li>
            <li class="nav-item" [class.menu-btn.show]="check" (click)="myfunction()">
                <a href="about.html" class="nav-link">About</a>
            </li>
            <li class="nav-item" [class.menu-btn.show]="check" (click)="myfunction()">
                <a href="work.html" class="nav-link">Work</a>
            </li>
            <li class="nav-item" [class.menu-btn.show]="check" (click)="myfunction()">
                <a href="contact.html" class="nav-link">Contact</a>
            </li>
          </ul>
      </nav>
</div>
</header>

app.component.scss

$primary-color: red;
$secondary-color: blue;

@mixin easeOut {
  transition: all 0.5s ease-out;
}

.container{
background-color: grey;
height:100px;
box-sizing: border-box;

}

a{
text-decoration: none;
color:white;

}
.btn-line{
color:blue;
}


header{
position: fixed;
z-index:2;
width:100%;
}

.menu-btn{
position: absolute;z-index:3;
right:35px;
top:35px;
cursor: pointer;
@include easeOut;

.btn-line{
width: 28px;
height: 3px;margin: 0 0 5px 0;background: white;
@include easeOut;

}
&.close {
transform: rotate(180deg);
.btn-line {

&:nth-child(1){
transform: rotate(45deg) translate(5px, 5px);
}
&:nth-child(2){
opacity: 0;
}
&:nth-child(3){
transform: rotate(-45deg) translate(7px, -6px);
}
}
}
}

.btn-line{
color:black;
}

app.component.ts

export class AppComponent {
title = 'menu';

 check:boolean=true;

 myfunction(){
 this.check=true;
 }

}

Answer №1

It seems that adding two classes at once with the [class.xxx.yyy] directive is not possible...

To apply both classes, you need to use two separate [class...] directives or utilize an ngClass directive, like this:

[ngClass]="{ xxx: check, yyy: check }"

UPDATE (based on a comment) In your template, there is code such as

[class.menu-btn.show]="check"
. It appears I misunderstood your intention if you don't want both the show and menu-btn classes added based on the variable check value - my apologies for that. However, remember that the class you want to add should be the only name in that directive (after class.). Therefore, if you wish to add the show class, use [class.show]="check". You can have multiple directives like this, each for a different class.

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 manage variables that are not present in a Vue.js template?

When working with vue.js templates, I often come across instances like this: {{ jobs[0].stages[0].node.name }} If a job has no stages, the entire template fails to load and vue.js admin throws this warning: Error in render: "TypeError: Cannot read prope ...

Attempting to retrieve a custom Google map with a specified user-defined radius

I'm currently working on implementing a feature that allows users to set the radius from their center location on a Google map. While I have most of the code in place, I'm struggling to get it fully functional. Below is the snippet of code I&apos ...

Is there a way for me to implement a "view more posts" button on

I need help figuring out how to hide the "Show More" button when there are no posts. I have created a showLoad function and an isLoad state variable, but I'm unsure of how to implement this. The button display logic is dependent on the isLoad state. ...

Could you explain the distinction between these two arrow functions?

I'm puzzled about why the second arrow function is effective while the first one isn't. //the first one doesn't function properly this.setState = () => { text: e.target.value, }; //in contrast, this one ...

tagit: update the label's value

I've been utilizing the jquery ui plugin https://github.com/aehlke/tag-it to incorporate tagging functionality into my project. This is how I am creating tags: $("#Input").tagit("createTag", "ABC"); My goal is to append additional text to the labe ...

Guide on using the react array map method to insert elements into a designated Id

Below is an example of an array containing IDs, items, and item notes descriptions. let sampleArr = [ { id:1, item:"item", notes:["one"] }, { id:2, item:"item2", notes:["one","two"] }, { id:3, item:"i ...

The functionality of Angular's swPush notificationonclick feature operates smoothly during development, but encounters issues when transitioning

I am currently working on an Angular website that includes push notifications, utilizing swPush for this feature. However, I have encountered an issue where the application fails to open a URL in production mode, although it functions correctly in developm ...

Unable to utilize Msal Angular 9 for accessing a personalized API

I am currently attempting to integrate MSAL with Angular 9 in order to gain access to a custom 'dynamics.com' API. Although I have successfully obtained a valid access token for the login API, I am facing issues when trying to utilize this token ...

I'm interested in developing a React function that generates recipe components based on a set of instructions provided in an array, along with a separate parameter specifying the recipe name

I am currently immersed in the book "Learning React" written by O'Reilly. The book mentions a method of creating components by using a function known as the "component creating function". It advises supplying the necessary parameters as the second par ...

Unable to modify the appearance of a Bootstrap multi-select component

After creating a multi-select feature using Bootstrap styling, I ran into an issue where trying to hide it with style="display:none" did not work as expected. Can someone shed light on why this is happening and provide a solution? <link rel="styles ...

Position items at the center of the grid in material UI

I am having difficulty centering the grid items of material UI. I have tried using the justifyItems and alignItems props as mentioned in the documentation, but I'm still unable to achieve the desired result. Can anyone provide some guidance? Below is ...

Exploring OpenLayers: How does the browser's console.log recognize the variable?

I attempted to log the ol_map from the browser console, but it returned an undefined error. The command seems to be working fine in the code itself. Why is this happening? I am currently using the Symfony framework along with Webpack Encore to manage my a ...

How to place an element in a specific location within the DOM using JavaScript

How can I position a created element in a specific place within the DOM using this code? Currently, it appends at the bottom of the page. var x = document.getElementById('options_10528_1'); var pos = document.getElementById('options-10528- ...

Leveraging AngularJS html5mode in conjunction with express.js

Client-side: when("/page/:id", { templateUrl: "partials/note-tpl.html", controller : "AppPageController" }); $locationProvider.html5Mode( true ); Html: <a ng-href="/page/{{Page._id}}">{{Page.name}}</a> Server-side: app.use("/pag ...

Retrieve posts from Angularjs

I am attempting to fetch tweets from a Twitter account using only AngularJS without the use of PHP or any other programming language. I have made several attempts but have not been successful. Additionally, I must utilize the 1.1 version of the Twitter A ...

Is the variable leaping to a superior scope?

A few days back, I encountered a strange bug in my code that has left me puzzled. It appears that a variable declared within a narrower scope is somehow leaking into a broader one. Any insights into what might be going wrong here? Here's a simplified ...

How can we generate an array of duplicated values from an array that already contains duplicates in JavaScript?

Given an array of objects like ["a","b","a","c","d","b"], how can I efficiently retrieve an array of the duplicate elements, such as ["a","b"]? Is there a method similar to u ...

Exploring nested rows with Angular's ui.grid component

After spending several hours attempting to implement a nested table within a single row using ui.grid, I am still unable to achieve the desired result. $scope.gridOptions.columnDefs = [ {name: 'id'}, {name: 'categoryName'}, ...

Exploring the concept of 'mapping' in jQuery: A guide to traversing an array with varying variable values

I need assistance in linking two unrelated data points together. I have an array that stores images at specific positions, and a variable that can hold different values (1, 2, or 3). My goal is to connect the array position (1, 2, or 3) with the variable v ...

Leveraging cy.tick() in combination with rxjs auditTime

An end-to-end test has been developed for a feature that utilizes ngrx state management. This particular feature gathers user inputs over a span of 60 seconds using the auditTime() operator and then sends them to an API endpoint. To speed up testing, inst ...