What is the alternative method for applying a CSS class in the click event in Angular 7 without relying on ng-Class or ng-Style?

Is there a way to dynamically add or remove CSS classes to HTML elements in Angular7 without relying on Ng-Style and Ng-Class directives? I'd like to achieve this functionality when clicking on the elements.

Appreciate any insights you can provide. Thanks!

Answer №1

If you're looking to toggle a class on click, this code snippet might help:

clicked(event) {
let currentClass = event.target.getAttribute('class') || '';
if (currentClass.includes('selected')) {
  currentClass = currentClass.replace('selected', '');
} else {
  currentClass += ' selected';
}
this.render.setElementAttribute(event.target, "class", currentClass);
}

Remember to

import { Renderer } from '@angular/core';
and include
constructor(private render: Renderer) { }

Check out the Stackblitz Demo for a live example

For more information on Renderer and using .replace(), or visit .replace() for further reference.

Answer №2

import { Directive, HostBinding} from '@angular/core';

@Directive({
  selector: '[myDirective]',
})
export class MyDirective {

  @HostBinding('class')
  elementClass = 'custom-theme';

  constructor() {
  }
}

You can now easily use the directive:

<div myDirective> </div>

If you prefer to use it directly inside a component:

import {Component, Renderer2} from '@angular/core';


@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent  {

  constructor(private renderer: Renderer) {}

  click(event) {
    renderer.addClass(event.target, 'popup');
  }
}

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 are the steps for importing a file into a React app that is built using Create React App as plain text?

Objectives I aim to showcase code snippets from the project itself for reference. I intend to keep the displayed code up-to-date with its implementation. I prefer not to remove myself from create-react-app This React project, built using create-react-ap ...

Creating synchronous behavior using promises in Javascript

Currently, I am working with Ionic2/Typescript and facing an issue regarding synchronization of two Promises. I need both Promises to complete before proceeding further in a synchronous manner. To achieve this, I have placed the calls to these functions in ...

What is the process of creating an instance of a class based on a string in Typescript?

Can someone please guide me on how to create an instance of a class based on a string in Nestjs and Typescript? After conducting some research, I attempted the following code but encountered an error where it says "WINDOWS is not defined." let paul:string ...

The return type of a getter is `any` if the object contains a method and is processed by a generic function

I am facing an issue with my code where the getter's return type is set to any, even though the actual return type should be clear. There are certain additional functions triggering this behavior: // This is necessary for reproduction const wrapperFun ...

Separating HTML content and text from a JSON response for versatile use within various sections of an Angular 2 application using Typescript

Hello there! I am currently utilizing Angular 2 on the frontend with a WordPress REST API backend. I'm receiving a JSON response from the service, however, the WP rest API sends the content with HTML tags and images embedded. I'm having trouble s ...

Ensuring the type of a specific key in an object

Seeking a more stringent approach regarding object keys in TypeScript. type UnionType = '1' | '2' | '3' type TypeGuardedObject = { [key in UnionType]: number } const exampleObject: TypeGuardedObject = { '1': 1, ...

Understanding a compound data type in TypeScript

Hey there, I'm new to TypeScript and I'm facing a challenge in defining the type for an object that might have the following structure at runtime: { "animals" : [ { name: "kittie", color: "blue" }, { name: ...

Why does the final value appear when passing an incrementing counter as a prop to multiple React Components created in a loop?

I am currently unraveling the concept of closures in JavaScript. Within this code snippet, I am cycling through the values of the 'items' array using a foreach loop. I have defined a let variable named "count" outside the scope of the loop. Afte ...

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...

Exploring the functionality of the Angular snackbar feature

I have created a simple snackbar with the following code: app.component.ts: ngOnInit(){ this.dataService.valueChanges.pipe( filter((data) => data === true), switchMap(() => { const snackBarRef = this.matSnackBar.open ...

Exploring the incorporation of an inclusive switch statement within a Redux reducer utilizing Typescript. Strategies for managing Redux's internal @@redux actions

After conducting extensive research, I have yet to discover a definitive answer to this query. There is a question posted on Stack Overflow that provides guidance on how to implement a thorough switch statement: How can I ensure my switch block covers al ...

Can wildcard paths be imported in React using Typescript?

Is there a way to dynamically import a React Typescript Component from a wildcard path, similar to the following code snippet? const Component = loadable( () => import(`../../../src/**/*/${component_name}`), ); I have searched numerous solutions on ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

Handlebar files are not compatible with Typescript loading capabilities

I am encountering an issue with my directory structure as follows : src |- server |- myServer.ts |- views |- myView.hbs dist |- server |- myServer.js The problem lies in the fact that the dist folder does not have a views subfolder, where the J ...

Looping Angular Components are executed

I am currently developing an Angular application and encountering an issue with my navbar getting looped. The problem arises when I navigate to the /home route, causing the navbar.component.html components to duplicate and appear stacked on top of each oth ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

Using Typescript to create a mapped type that allows for making all properties read-only, with the exception of

I encountered a problem where I didn't want to repeatedly rewrite multiple interfaces. My requirement is to have one interface with full writing capabilities, while also having a duplicate of that interface where all fields are set as read-only excep ...

$(...).parentElement is not a function - Troubleshooting a Problem with WebDriver IO and TypeScript

Alright, the objective is simple. I need to ascend from the root to obtain its parent element. Following the webdriver documentation, it should resemble something like this: it('should retrieve the class from the parent element', async () => { ...

Converting JavaScript object data to x-www-form-urlencoded: A step-by-step guide

I am trying to convert a JavaScript object into x-www-form-urlencoded. Is there a way to achieve this using Angular 2? export class Compentency { competencies : number[]; } postData() { let array = [1, 2, 3]; this.comp.competencies ...

Managing the Cache in IONIC2

After developing an App using IONIC 2, I realized that all my pages require loading through REST API. This can be frustrating as they get reloaded in every tab even when there are no updates. To improve this issue, I am planning to implement a caching sys ...