Click event in parent component toggles class in child component in Angular 2

I'm facing a challenge in toggling a class on and off using a click event. The issue arises from the fact that the click event is in the parent component while the class is in the child component. Although I can initialize the child with the class using the @Input() decorator, I'm unable to toggle the class later on.

import { Component, AfterViewInit, Input, OnInit } from '@angular/core';
import { SidebarComponent } from './components/sidebar/sidebar.component';

@Component({
   moduleId: module.id,
   selector: 'body',
   host: {
      '[class.navMdClass]' : 'navMdClass',
      '[class]' : 'classNames'
   },
   templateUrl:'app.component.html' ,
   directives:[SidebarComponent],    
})
export class AppComponent implements OnInit {
   private isClassVisible:boolean;
   constructor () {    

   }
   ngOnInit() {
      this.isClassVisible=true;
   }
   toggleClass() {
      this.isClassVisible = !this.isClassVisible;       
   }
}
//Child component
import { Component, Input, EventEmitter, OnInit,SimpleChange } from '@angular/core';
@Component({
    moduleId: module.id,
    selector: 'sidebar',
    templateUrl:'sidebar.component.html' 
})

export class SidebarComponent implements OnInit{
    @Input() isClassVisible:boolean;

ngOnInit() { }
}
//Parent click event triggers toggleClass
<div class="nav toggle">
          <a (click)="toggleClass();" href="#" id="menu_toggle"><i class="fa fa-bars"></i></a>
      </div>
//Child div where target class is
<div class="left_col" [class.scroll-view]="[isClassVisible]" >

Answer №1

It is essential that you eliminate the brackets surrounding [class.scroll-view]="[isClassVisible]" and instead use

[class.scroll-view]="isClassVisible"

Answer №2

I discovered a resolution to the issue by implementing a method that involves passing class names as properties to child components. If there are multiple classes to be passed to different sections, they can be included in an array property and displayed in the appropriate locations.

//parent component
import { Component, AfterViewInit, Input, OnInit } from '@angular/core';
import { SidebarComponent } from './components/sidebar/sidebar.component';

@Component({
   moduleId: module.id,
   selector: 'body',
   host: {
      '[class.navMdClass]' : 'navMdClass',
      '[class]' : 'classNames[0]'
   },
   templateUrl:'app.component.html' ,
   directives:[SidebarComponent]


})
export class AppComponent{

   navMdClass:boolean;
   classNames:Array<any>;

   constructor () {
      this.navMdClass=false;

      this.classNames = ['nav-md', 'scroll-view',  'sidebar-footer'];
   }

   toggleClass() {

      this.navMdClass = !this.navMdClass;
      if(this.navMdClass==false){ this.classNames[0] = 'nav-md'; this.classNames[1]="scroll-view"; this.classNames[2]="sidebar-footer"}
      if(this.navMdClass==true){  this.classNames[0] = 'nav-sm'; this.classNames[1]=""; this.classNames[2]="sidebar-footer-hide"}
      //console.log(this.classNames[0]);
   }
}
//child component
import { Component, Input, EventEmitter, OnInit, SimpleChange, OnChanges  } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'sidebar',
    templateUrl:'sidebar.component.html',
    properties: ['cls']
})

export class SidebarComponent{
    @Input() classNames:Array<any>;
}

//Parent click event triggers toggleClass
<div class="nav toggle">
          <a (click)="toggleClass();" href="#" id="menu_toggle"><i class="fa fa-bars"></i></a>
      </div>
//Sidebar selector in parent is where you pass the cls property declared in child component and pass it the classNames array from the parent component
<sidebar [cls]="classNames"></sidebar>
//Child div where target class is
<div class="left_col {{cls[1]}}" >
<div class="{{cls[2]}}" >

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

different ways to retrieve component properties without using inheritance

In order to modify certain properties of components after login, such as the "message" property of HomeComponent and the "age" property of UserComponent, I am unable to inherit the component class. What are some alternative methods to achieve this? Authen ...

Universal key and attribute retrieval function

Currently, I am attempting to analyze the characteristics of objects within arrays. In order to maintain type safety, I am utilizing a getter function to access the child object of the array objects (if necessary) that contains the specific property to be ...

Issue in Ionic 2: The function AppScripts.serve is throwing an error due to TypeError

Currently, I am working on an Ionic 2 project using Angular to develop a small app. When I attempt to run 'ionic serve', I encounter the following error. I have already attempted to completely delete the 'node modules' folder and run &a ...

Issue with Angular routing: encountering a 404 error indicating page not found

I'm facing an issue with routing in my Angular application. All components were working fine previously, but suddenly none of the components are accessible today. Whenever I try to access a specific path, I receive an "error 404 /test" message from An ...

Determining the existence of a specific value within an array using JavaScript

I am looking at a JavaScript Array business: [{ "id": 22, "name": "Private", "max_mem": 0, "gen_roomtype_id": 4, "status": 1, "type": 0, "set_value": 1 }, { "id": 6, "name": "Standard ward", ...

Angular 5 ngx-modialog issue TS2307: Module 'ngx-modialog/plugins/vex' not located

After installing module ngx-modialog using the Angular 5 CLI like this: npm install --save ngx-modialog I then added it to my app.module.ts: import { VexModalModule } from "ngx-modialog/plugins/vex"; import { ModalModule } from "ngx-modialog"; @NgModul ...

Trouble Ensuring First Radio Button Is Checked in Angular 6

I'm working on setting the first radio button in a group to be checked by default. Within my application, I have 6 tabs each containing a set of scales that need to be displayed as radio buttons. The goal is to have the first button in each tab check ...

Metamorphosed Version.execute SourceText and TypeScript Writer

I'm currently working on transforming a TypeScript source file and I have successfully made the necessary changes to the code. Despite seeing my transformed node in the statements property of the transformed source file, the SourceFile.text property d ...

Filling an Angular table with data from Google Sheets

I am looking to display data from Google Sheets in a table using Angular 6. I am utilizing the npm package get-sheet-done to create a JSONP and retrieve the data from Google Sheets as JSON. This allows me to update the data in my table dynamically when cha ...

The form input is not being populated as expected after being retrieved from the service

Currently, I am constructing a form using Angular 5 within a material popup that includes both a select box and text fields. The issue arises when the select box value is fetched from a service, causing a delay in populating the select box for the user. ...

Trouble with incorporating ellipses across multiple lines in Angular 7

I am attempting to display ellipses in a multi-line block using Angular, but I am encountering the following problem. component.html <div class="test" [innerHtml]="anchor1.length >= 200 ? anchor1.substring(0,242) + '...' : anchor">< ...

Sharing data between sibling components becomes necessary when they are required to utilize the *ngIf directive simultaneously

Within my parent component, I am hosting 2 sibling components in the following manner: <div *ngif="somecode()"> <sibling1> </sibling1> </div> <div *ngif="somecode()"> <sibling1 [dataParams]=sibling1object.somedata> ...

Error message indicating that the Angular validator function is not properly defined

I'm currently working with Angular FormBuilder and implementing my own validation logic. In my formBuilder configuration, I have defined the following: this.form = this.formBuilder.group({ password: ['', [Validators.required, this.matcher ...

Pressing the tab key while using Angular will halt any additional processes from running

I recently integrated a search bar into my Angular application. When I enter text in the input field, a customized dropdown menu appears below it. However, when I press the tab key, I expect the dropdown to close and for the focus to shift to the next inpu ...

The switchMap function in Angular does not trigger the async validator as expected

To ensure that the username entered by the user is unique, I am sending an HTTP request for every input event from the target element. It is important to debounce this operation so that only one HTTP request is made for X consecutive input events within a ...

Improved with TypeScript 4.1: Fixed-Size String Literal Type

The latest updates from the TypeScript team have shown significant improvements in string literal typing (4.1 & 4.2). I'm curious if there's a way to define a fixed length string. For example: type LambdaServicePrefix = 'my-application- ...

Implementing Pagination in Django REST API and Angular 11

Attempting to tackle the challenge of integrating a Django REST pagination object with Angular 11. Despite not being a coding newbie, navigating through Angular is relatively new to me. The current setup involves Django REST api pagination set at every 6 ...

Having trouble deploying an Angular Universal app to an AWS S3 bucket with server-side rendering (SSR

Transitioning from an Angular9 application to make it SEO friendly required me to switch to Angular Universal SSR. I followed the steps below: Ran the command: ng add @nguniversal/express-engine Ran the command: npm run dev:ssr Ran the command: npm run bu ...

Apollo Client is not properly sending non-server-side rendered requests in conjunction with Next.js

I'm facing a challenge where only server-side requests are being transmitted by the Apollo Client. As far as I know, there should be a client created during initialization in the _app file for non-SSR requests, and another when an SSR request is requi ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...