I want to modify a class in Angular 8 by selecting an element using its ID and adjust the styling of a div

Is it possible to dynamically add and remove classes using getElementById in Angular 8? I need to switch from 'col-md-12' to 'col-md-6' when a user clicks on the details icon.

I also want to modify the style of another div by setting display: block.

component.html

 <div class="col-md-12" id="demo">
      <div class="example-container mat-elevation-z8 mt-5">
        <table class="table table-striped">
          <tbody>
            <tr>
              <th>Points</th>
              <th>###</th>
            </tr>
            <tr *ngFor="let user of usersArray" >
              <td>
                {{user.score}}
              </td>
              <td>
                <i class="material-icons text-primary pointer" (click)="details()">account_circle</i>
              </td>
            </tr>
          </tbody>

        </table>

      </div>
    </div>

After changing the class, I want this div to be displayed

  <div class="col-md-6" style="display: none;" >
        <div class="userDetails">
            <img src="../../assets/images/user.png">
            <span class="mx-3"> <b>Shubham Patil</b></span>
            <div class="example-container mat-elevation-z8 mt-4">
              <table class="table table-striped rounded">
                <tbody>
                  <tr>
                    <th>Topics</th>
                    <th>Points</th>
                  </tr>
                  <tr >
                    <td>
                      Why me
                    </td>
                    <td>
                      300
                    </td>
                  </tr>
                </tbody>
              </table>
              </div>
        </div>
    </div>

component.ts

element: HTMLElement;

 details(){
    this.element = document.getElementById('demo').classList.remove("col-md-12") as HTMLElement;
    this.element = document.getElementById('demo').classList.add("col-md-6") as HTMLElement;
    console.log("change")
}

Answer №1

Give this a shot:

In your template file:

<div class="col-md-12" id="demo" #demo>
   ...
   <td>
    <i class="material-icons text-primary pointer" (click)="details(demo)">account_circle</i>
   </td>
   ...
</div>

and in the corresponding .ts file:

details(elem: HTMLElement) {
  console.log(elem.className, 'before');
  elem.className = 'col-md-6';
  console.log(elem.className, 'after');
}

Answer №2

One way to apply conditional styling in Angular is by using the ngClass directive. For more information, refer to this official documentation.

Answer №3

To implement this in Angular, the recommended approach is to link variables in the component file with the template using Angular's template language. You can refer to the template syntax section in the Angular documentation for detailed information.

component.html

 <div id="demo"
    [class.col-md-12]="!isShowingDetails"
    [class.col-md-6]="isShowingDetails"> <!--"[class.my-class-name] syntax for dynamically adding or removing classes based on the assigned property value -->
      <div >
        ...
            <tr *ngFor="let user of usersArray" >
              <td>
                <i class="material-icons" (click)="showDetails()">account_circle</i>
              </td>
            </tr>
         ...
      </div>
    </div>
    <div class="col-md-6" *ngIf="isShowingDetails"> <!--Added *ngIf directive for showing and hiding details HTML -->
        <div class="userDetails">
           ...
        </div>
    </div>

component.ts

@Component({
    ...
})
class MyComponent {
    isDisplayingDetails = false;

    showDetails() {
        isDisplayingDetails = true;
    }

}

For further understanding, you can check out the class binding and *ngIf sections in the Angular documentation.

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

Transform the appearance of Angular Material's table with a new design

Currently, I am working with Data-Table from angular material and I am looking to customize the table style to better suit my needs. I'm wondering how I can remove the border/frame from the table and eliminate the 3D effect on the frame. Any suggesti ...

Dealing with a sequence of deletions in Angular 4

When working with a ReplaySubject of size 3 and a delete chain that must be in order, I encountered an issue. After the deletion process is completed, I need to redirect the user. However, when subscribing to this ReplaySubject method, it sends "here fin ...

p-menu fails to appear

I'm currently experimenting with Primeng and Angular 2 to put together a basic menu. Take a look at my code snippet: import {Component, OnInit} from '@angular/core'; import {Menu, MenuItem} from 'primeng/primeng'; @Component({ ...

What steps do I need to follow to write this function in TypeScript?

I am encountering a problem when building the project where it shows errors in 2 functions. Can someone please assist me? The first error message is as follows: Argument of type 'IFilmCard[] | undefined' is not assignable to parameter of type &a ...

Error: Vue Prop is undefined and cannot be utilized within a v-for loop when using TypeScript and decorators

Hey there, I'm currently utilizing Vue along with typescript and facing an issue with props in v-for where it's not rendering anything. Check out the code snippet below for reference I've experimented with computed props, setting default va ...

Limiting the height of a grid item in MaterialUI to be no taller than another grid item

How can I create a grid with 4 items where the fourth item is taller than the others, determining the overall height of the grid? Is it possible to limit the height of the fourth item (h4) to match the height of the first item (h1) so that h4 = Grid height ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

Error: A cyclic dependency cannot be instantiated. The ApplicationRef ("[ERROR ->]") is occurring in the NgModule AppModule within ./AppModule@-1:-1

I recently implemented the following code in my app.module.ts file: providers: [ AppConfigService, { provide: APP_INITIALIZER, useFactory: (config: AppConfigService) => () => config.getAppConfig(), ...

Using Angular 8, you can create a reactive form that includes a custom ng-select component which has

My custom angular reactive form includes a ng-select component along with other elements. I have implemented the following code to validate the form: private validateCustForm() { this.validation.touchFormControls(this.appointmentForm); if (this.ap ...

Building a Next.js application that supports both Javascript and Typescript

I currently have a Next.js app that is written in Javascript, but I am looking to transition to writing new code in Typescript. To add Typescript to my project, I tried creating a tsconfig.json file at the project root and then ran npm install --save-dev ...

Retrieving an image from the image repository

Having issues with Ionic 3, Angular CLI 7, and Angular 5. I'm encountering difficulties in fetching an image from the library. The problem arises when calling getPicture function. The error message reads: “Object(WEBPACK_IMPORTED_MODULE_1__ioni ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...

Unable to declare a string enum in TypeScript because string is not compatible

enum Animal { animal1 = 'animal1', animal2 = 'animal2', animal3 = 'animal3', animal4 = 'animal4', animal5 = 'animal5' } const species: Animal = 'animal' + num Why does typescr ...

Exploring the implementation of initiating paypal in NestJs using Jest testing framework

Currently, I am creating a test for a method within NestJs that is responsible for initiating a Paypal Payment intent. When I execute either the yarn test:watch or simply yarn test command, the test described below runs successfully and passes. However, up ...

Ways to conceal an element in Angular based on the truth of one of two conditions

Is there a way to hide an element in Angular if a specific condition is true? I attempted using *ngIf="productID == category.Lane || productID == category.Val", but it did not work as expected. <label>ProductID</label> <ng-select ...

What are the steps to incorporating the pick function in TypeScript?

The TypeScript documentation mentions a pick function that is declared but not implemented. In an attempt to create a simplified version, I wrote the following: function pick<T, K extends keyof T>(obj: T, key: K): Pick<T, K> { return { [key]: ...

What is the best way to create a React component that renders a class component as a functional component?

My Objective: At the moment, I am in the process of developing an AuthUserRole HOC component to manage user roles like Manager and Employee. However, I encountered a tutorial that uses a functional component to return a class component as referenced here. ...

What steps should I take to display the outline of an Angular Material Icon in my Angular application?

Currently, I have <mat-icon>info<mat-icon> The result is the info icon with a filled color. However, my intention is to display just the outline of the icon. How can I achieve that? The specific icon I am looking for can be found at https:/ ...

Is there a way for me to retrieve the bodyHeight attribute of ag-grid using public variables or data?

Working on a project using ag-grid community react. The main feature is a scrollable section filled with data, which can range from one piece to millions of pieces. I'm also incorporating a footer component for the grid that needs to adjust its height ...

Utilizing Angular's NgFor directive to showcase the elements within the array

Just diving into Angular and attempting to access the values within postdata. However, I'm running into an issue where only the first value is being retrieved when I try to iterate over it. Here's a snippet of my code: posts; constructor(priva ...