What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of the array at that specific index. For instance, if arr[0]=70, then the width of div id='bar0' should be 70%. This visualization will be triggered when I click on the "generate an array" button, followed by clicking the "sort" button to sort the entire array.

However, despite my efforts, I keep encountering errors in the developer console. Below is a snippet of my code from app.component.ts:

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent {
  str: string = "";
  // other variables and functions here
}

And here is the corresponding code from app.component.html:

<div class="nav">
    <a href="#">Home</a>
    <a href="#">Open Visualizer</a>
    <a href="#">Technologies Used</a>
    <a href="#">About</a>
</div>
<section>
    <button (click)="generateArray()">Generate Array</button>
    <button (click)="sortt()">Sort</button>
    <div class="bar" *ngFor="let items of arr; let i=index;" [id]="'bar'+i"></div>
</section>
<router-outlet></router-outlet>

I seem to be missing something crucial here. Can you help me figure out what might be causing these errors?

Answer №1

Typically, ViewChildren or ViewChild are used to obtain references to HTML elements.

In Angular, you have the ability to manually create and animate elements. For example, you can define a function like this:

  animate(element:any,width:string)
  {
      const myAnimation = this.builder.build([
        animate(this.timing, style({ width: width })),
        ]);
      this.player = myAnimation.create(element);
      this.player.play();
  }

If you have elements like this in your HTML:

<button (click)="click()">Animate</button>
<div *ngFor="let i of [0,1,2,3]" #bar 
    style="height:1rem;width:0px;background-color:red;margin-bottom:.5rem">
</div>

You can then include the following code in your TypeScript file (.ts):

  @ViewChildren("bar") bar: QueryList<ElementRef>; //<--these are your bars
  timing = "450ms ease-in-out";

  private player: AnimationPlayer;

  constructor(private builder: AnimationBuilder) {}

  click() {
    this.bar.forEach(x => {
      this.animate(x.nativeElement, 100 * Math.random() + "%");
    });
  }

For a live demonstration, check out this StackBlitz link.

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

Adjust and modify class when resizing the window

I've encountered a challenge with my Bootstrap Modal when trying to set the width to 750px on large desktops. When resizing the window to a smaller size, the modal loses its responsiveness. To tackle this, I added a class to the modal to give it a fix ...

Use PHP to highlight the row that has been selected in an HTML table

I am currently working on a project where I have styled multiple HTML tables on my website using alternating gray and white bands. Now, my goal is to highlight the selected row in a darker shade of gray. I have experimented with various solutions, and the ...

I encountered a function overload error while creating a component for the API service

As a developer venturing into API design with a backend server that handles client-side calls, I find myself grappling with Typescript, transitioning from a Java background. Encountering the error message "No overload matches this call" has left me seeking ...

Retrieve information from the third section by utilizing ajax

My current setup involves: Having a form in form.php for inserting data, Displaying data in table format with pagination on display.php, and Using validation.js for validating form data along with the following function: $('#pagiCount a'). ...

Implementing Batch File Uploads using Typescript

Is there a way to upload multiple files in TypeScript without using React or Angular, but by utilizing an interface and getter and setter in a class? So far I have this for single file upload: <input name="myfile" type="file" multi ...

The JestImportMeta interface is mistakenly extending the ImportMeta interface, causing an error

While transitioning from jest version 27 to v29, I encountered this issue: node_modules/@jest/environment/build/index.d.ts:329:26 - error TS2430: Interface 'JestImportMeta' improperly extends interface 'ImportMeta'. The types returned ...

Changing an Array into JSON format using AngularJS

I am attempting to switch from a dropdown to a multiselect dropdown. <select name="molecularMethod" class="form-control" ng-model="request.molecularMethod" multiple> It is functioning properly. However, when items are selected, it generates an arra ...

Learning to access a base64 encoded PDF file using JavaScript

var ajaxSettings = { url: urls.orders.list+"/"+singlePacket.requests[0].order_id+"/labels", //retrieve labels with ShipperAssigned status type: "GET", contentType: "application/json", headers: { "Authorizatio ...

comparing multiple values separated by commas with JavaScript

I need validation using a comma-separated value format. Within the illustration, there are two fields: "Saloon Price" (value: 10,10,10,10) and "Saloon Offer Price" (value: 11,11,11,11). The first value must be less than the second. Saloon price Value > ...

Rotating the transform causes the div to be pushed beyond the screen boundaries and renders

html, body { margin: 0; padding: 0; overflow-x: hidden; } /*HEADER*/ #header { background: blue; background-attachment: fixed; background-size: cover; width: 100vw; height: 100vh; } .btn-1, .btn-2, .btn-3 { background ...

Implementing Constants in Angular 2: Best Practices

Within my Angular 2 project, I have a crucial object known as translation that stores various strings utilized in multiple forms. This global configuration appears as follows: public translator = { 'performance_standard_time_deviation&apo ...

The functionality of the dynamic drag and drop form builder is not functioning as expected in Angular 12

I am currently developing a dynamic form builder using Angular version 12. To achieve this, I decided to utilize the Angular-Formio package. After installing the package and following the steps outlined in the documentation, I encountered an issue. The i ...

The white-spaces in Quill JS do not retain their original formatting

I recently integrated Quill JS editor into my website. During testing, I noticed that any text inputted after a white space gets emitted when alerting the content. Below is the HTML code snippet: <div id="postCommentEditor" class="postCo ...

How can we initiate an AJAX request in React when a button is clicked?

I'm fairly new to React and I'm experimenting with making an AJAX call triggered by a specific button click. This is how I am currently using the XMLHttpRequest method: getAssessment() { const data = this.data //some request data here co ...

It is impossible to alter the data contained within the input box

Objective: Upon clicking a button to display the modal, the selected data (first and last name) should be inserted into an input box and editable. The user should be able to modify the data. Issue: The data entered into the input box cannot be edited ...

detecting syntax errors in CSS with @media queries and keyframes

/*general CSS setting for all device types above hd*/ * { margin: 0; padding: 0; } #watchonly { display: none; } ...

Tips for setting the style of child components in a ReactJS project with CSS modules, classNames, and JSX syntax

Currently in the process of setting up a project using React JS and I am interested in incorporating auth0 for authentication purposes, along with potentially integrating some serverless functions. auth0 conveniently offers a pre-made "seed" project at ht ...

Updating a webpage using Ajax in Django

I've been diving into Django and am eager to implement ajax functionality. I've looked up some examples, but seem to be facing a problem. I want to display all posts by clicking on a link with the site's name. Here's my view: def archi ...

Upon clicking the IconButton within the ImageListItemBar, reveal the image within a Material-UI Dialog

import * as React from 'react'; import Box from '@mui/material/Box'; import ImageList from '@mui/material/ImageList'; import ImageListItem from '@mui/material/ImageListItem'; import ImageListItemBar from '@mui/m ...

Tips for embedding the <img> element inside the <a> element

I'm attempting to place an image within a hyperlink tag. Current code: <div class="Sample"> <a href="http://www.Sample.com"> <img src="http://www.Sample.com/Sloth.jpg"> </a> </div> I wish to add <img class= ...