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

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

The process of uploading a file to the server directory via ajax is not functioning correctly. Despite attempts to upload the image, it does not successfully transfer to the designated upload

I am encountering an issue with uploading files to the server upload directory using AJAX. The image is not being successfully uploaded and I keep receiving a "connection reset" error. Can you please review my code below to see if there are any mistakes? T ...

Troubleshooting Issue with Public File Serving in ExpressJS Deployment (NodeJS/Express)

The directory structure of my project is organized as follows: my_project server.js app.js | | - public | ----------| images | javascripts | stylesheets | -------------- imgs ---scripts.js ---styles.css | | - routes | | - views | ...

Monitoring changes within a factory

Hey there! I've got this shared_service factory that's being used by my menu and other elements on the page. angular.module('shared_service', []). factory('Shared', function($scope){ var shared_service = { ...

What steps are involved in creating a circular shape on canvas?

I am trying to create a circular shape in the canvas using the code below. The code involves moving an object with keyboard keys, and I need help making the canvas shape into a circle without affecting the functionality of the code. I attempted to modify t ...

Issue: The configuration for the rule "no-empty-interface" in .eslintrc.js is not valid

Is it acceptable to include an empty interface like the one shown below in the eslintrc.js file? interface RoutesProps {} ...

Words program with the header feature incorporated

Hello, I am currently working with Laravel to build an HTML page and have successfully converted it to MS Word. However, I am now trying to add a header inside. Can anyone help me achieve this? Here is a snippet of my code: <body> <a class= ...

Adding options to a dropdown menu dynamically while editing a form with the help of javascript

I have a dropdown like in below:- <form name="depositForm" action="<?php echo site_url('ajax_funds/deposit_funds'); ?>" id="depositForm" class="page-form-main form-horizontal " autocomplete="off" method="post"> <div class="form- ...

Error in Visual Studio with Angular 2 build: 'Promise' name not found

I recently started exploring Angular2 and followed the instructions provided in this quickstart guide: https://angular.io/guide/quickstart Everything seems to be working well after running npm install, but now I want to work on it within Visual Studio usi ...

Having trouble adding Bootstrap to Angular with Webpack? You might come across the error message: "File to import not found or unreadable: ../bootstrap/sc

I have decided to incorporate Bootstrap into my project. My attempt at installation involved using "bootstrap": "^4.0.0-alpha.5" I followed a tutorial found at https://github.com/AngularClass/angular2-webpack-starter/wiki/How-to-use-Bootstrap-4-and-Sass- ...

The whitespace issue stems from the div element __next-build-watcher generated by next js and usecontext

There's a notification bar at the bottom of my page that lets the user know when their email has been sent. This bar is generated using useContext in React/Next.js. To see the code, check out this Codebox link: Code However, I've noticed there ...

Valid ways to ensure that a CSS image expands outside the boundaries of the containing div

I have inserted an image using the following CSS code: .imgtemp { float:right; top:0px; left:0px; overflow:visible; width:100%; } Although I have added the div tag to display it on the page, ...

Unable to bind service data to the kendoUI grid

I'm in the process of developing an angular 4 component incorporating kendoUI. While using the kendoUI grid to display json data, I've encountered a debugging issue. The service seems to be retrieving records successfully, but for some reason, th ...

Sending numerous arguments to getStaticPaths() in nextjs

I am looking to create two different routes: /midterm/cs611 /finalterm/cs611 My goal is to display distinct content when accessing the /midterm/cs611 endpoint, and different content when accessing the /finalterm/cs611 endpoint. However, I am running into ...

What could be causing the change event to be triggered in a v-text-field when I press enter, despite not making any changes?

How come the @change event triggers in a v-text-field when I press enter, even if I haven't made any changes? HTML <div id="app"> <v-app> <v-content> <v-container> <v-text-field @change=" ...

Learn the steps to Toggle Javascript on window resize

Is there a way to toggle Javascript on and off when the window is resized? Currently, resizing the window causes the navigation bar to stick and remain visible above the content. <script> if ( $(window).width() <= 1200 ) { }else{ $('nav& ...

What is the best way to change the font size in HTML?

After carefully analyzing the image provided, I encountered an issue while attempting to incorporate the code display:block. However, no changes were reflected. Can you identify what may be causing this discrepancy in my text? How can this issue be recti ...

JavaScript client side event that references the sender object ID in an aspx file

Can someone provide assistance with an issue in the code block below? function(s, e) { form1.hfRaiseEvent.value = s.ID; } This particular function is triggered when the Client Side Click Event occurs. From my understanding, s refers to the Sender Obj ...

A recursive approach for constructing a tree structure in Angular

Currently, I am working on a project involving the implementation of crud functions. To display the data in a tree-like structure, I am utilizing the org chart component from the PrimeNg library. The data obtained from the backend is in the form of an arra ...

Factory not properly updating AngularJS controller

I am facing an issue with two controllers and one factory in my AngularJS application. The first controller sends an http request to a server, receives a string in response, and stores it in the factory. However, the second controller does not update with ...