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

Utilize *ngIf to conceal a row within a material table

I'm struggling with hiding a row after clicking a button in the mat-table. I can't figure out where to place the *ngIf directive. I attempted using it on ng-container, but it didn't work as expected. Below is the excerpt from my HTML file. ...

Encountering an issue with applying D3 fill to a horizontal stacked bar chart in Angular using TypeScript. When using .attr("fill", ..) in VSC, an error stating "No overload matches this call" is displayed

My goal is to create a stacked horizontal bar chart in d3, and I've been following the code example provided here. To showcase my progress so far, I have set up a minimal reproduction on stackBlitz which can be found here. While there are no errors ...

Encountering a NullInjectorError in Angular while utilizing dynamic module federation when importing a standalone component along with

My main goal is to develop a shell application acting as a dashboard without routing, featuring multiple cards with remote content (microfrontend standalone component). I have been following a tutorial that aligns closely with my requirements: . The reas ...

Issues with implementing PrimeNG Data List component in Angular 4

I'm encountering an issue with my data list in primeng as I try to run the app: Can't bind to 'value' since it isn't a known property of 'p-dataList' The HTML file looks like this: <p-dataList [value]="cars"> ...

Facing issues while trying to update Angular from version 12 to 13 due to conflicting peer dependencies

I'm in the process of upgrading an Angular project from version 12 to 13, following the guidelines provided on the Angular update website https://update.angular.io/?v=12.0-13.0. Before starting the upgrade procedure, this is how the package.json file ...

UI components displaying varying data retrieved from Redux, despite having identical user interfaces

Currently, I have a component that receives data from the Redux store using useSelector. The UI remains the same, but I need to change where the data is coming from by passing the selector through props. My first question is: Is it acceptable to pass the ...

Preventing the upload of empty images in an angular application

When selecting multiple images for upload, I sometimes need to make changes or delete the chosen images before actually uploading them. However, if any of the selected images have a size of 0B, I want to stop the upload process for all images, not just the ...

Issue: Unable to call method "call" as the model "Model" has not been initialized within a Sequelize instance. Kindly ensure that "Model" is added to a Sequelize instance before attempting to use the "call" method

Author.ts import {Table, Model, Column, DataType} from 'sequelize-typescript' @Table export class Author extends Model<Author> { constructor(){ super(); } @Column(DataType.STRING) fname: string @Column(DataType.STRING) lname: strin ...

The Node.js application is having trouble connecting to the Angular application on port 3000 when the Angular app is hosted on a remote machine

I'm facing an issue with my Nodejs app not being able to connect with the Angular app on port 3000 when the Angular app is hosted on a remote machine. However, everything works fine when both apps (Nodejs and Angular) are hosted on the same machine. C ...

Updating a property in a JavaScript object using Angular

Working with Angular, I have a dataset: export class AppComponent { data = [ { "area1": { "format": "changethis" } ] I am looking to develop a function that can alter the value of a specific key. For e ...

The parameter type 'typeof LogoAvatar' cannot be assigned to the argument type 'ComponentType<LogoProps & Partial<WithTheme>'

Why is the argument of type typeof LogoAvatar not assignable to a parameter of type ComponentType<LogoProps & Partial<WithTheme>? Here is the code snippet: import * as React from "react"; import { withStyles } from "@material-ui/core/style ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

Having trouble with firebase admin code completions not functioning properly in vscode?

I've attempted to install the Typescript integration for Firebase using: npm install --save-dev @types/firebase Unfortunately, I have not had any success. The "firebase-admin" and "firebase-functions" packages do not provide code completion or intel ...

Is it feasible to mock a defined function in Typescript for a unit test scenario?

Currently, I am working on typescript code that compiles into javascript, gets bundled with rollup, and is utilized by a framework. This framework exposes a library to me in the global scope, taking the form of a function: fun({ prop1: number, ...

Typescript: The original type cannot be indexed with a type-mapped type

I'm currently working on a class where I need to define a method that returns an object with keys based on the generic type inferred by the compiler. However, I've encountered an issue with the code snippet below. The compiler is indicating that ...

React Router throwing an error about an Invalid Hook Call when attempting to use useState in index.tsx instead of App.js

I'm currently learning React Router by following a video tutorial, but I've run into an issue. In my Stackblitz project, there is no App.js file, so I've placed everything inside index.tsx. However, now I need to use the line ----> const ...

Uh-oh! A circular dependency has been detected in the Dependency Injection for UserService. Let's untangle this web and fix the issue!

Encountering the following error: "ERROR Error: Uncaught (in promise): Error: NG0200: Circular dependency in DI detected for UserService." The auth.component.ts utilizes the UserService and User classes, while the user.service.ts only uses the User class. ...

Utilizing images in a compiler run with the option of `allowJS:true` is key

Looking to develop a React Native library using JavaScript instead of typescript, but want to leverage TSC for its ability to generate type declarations from jsdoc comments. However, encountering an issue where local images are not included when the ts com ...

Guide to showcasing a stomp client's message in the view without having to refresh the page when a new message is delivered

I'm in the process of setting up a chatroom with Angular and web-socket. I want to update the view with new messages from the socket without having to refresh the page. The message is appearing in the log console but not on the page. Any suggestions w ...

Issue with displaying data using a custom pure pipe and boolean in ngIf condition

For my current web project, I require a friendship/follow feature. There are two roles involved: admins and regular users. Regular users have the ability to follow other users, while admins do not possess this capability. When a user wishes to follow anot ...