Code in Javascript to calculate the number of likes using Typescript/Angular

I have encountered a challenge with integrating some JavaScript code into my component.ts file in an Angular project.

Below is the code snippet I am working on:

ngOninit() {
  let areaNum = document.getElementsByClassName("some-area").length;

  // The problem lies within the following code snippet:
  for (let area of document.getElementsByClassName("some-area")) {
    area.style.height = 100 / areaNum + "%";
  }
}

The error message received reads as follows:

Type 'HTMLCollectionOf<Element>' must have a '[Symbol.iterator]()' method that returns an iterator.ts(2488)

How can this issue be resolved to ensure functionality within the Angular framework?

Answer №1

Document.getElementsByClassName provides a live HTMLCollection. Check out the details on MDN website

You can easily convert it into an array by using Array.from

Array.from(document.getElementsByClassName("some-area"))

Answer №2

Styling with CSS, No Javascript Needed

Why are you using Javascript to update HTML in Angular functions? Your code should focus on styling the parent element of some-area by setting it to display: flex, and applying flex: 1 to the children elements.

By implementing this style, adding 1 or 1000 elements will always display correctly without any manual adjustments.

Avoid manipulating styles from javascript whenever possible - let Angular only handle adding and removing elements.

Objective:

You aim to evenly space the some-area elements within their container so each of their heights is 100% / number of elements.

This desired layout can easily be achieved using CSS Flexbox, eliminating the need for JavaScript intervention.

Enhanced Approach:

.container {
  /* Common Style Properties */
  height:100vh;
  gap:10px;

  /* Core Styling */
  display: flex;
  flex-direction: column;
}

.some-area {
  /* Common Style Properties */
  background-color:red;
  color:#fff;
  padding:10px;
  
  /* Core Styling */
  flex-grow: 1;
}
<div class="container">
  <div class="some-area">some content</div>
  <div class="some-area">some content</div>
  <div class="some-area">some content</div>
  <div class="some-area">some content</div>
</div>

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

Exporting Axios.create in Typescript can be accomplished by following a few simple

My code was initially working fine: export default axios.create({ baseURL: 'sample', headers: { 'Content-Type': 'application/json', }, transformRequest: [ (data) => { return JSON.stringify(data); } ...

Guide on exporting a function from a module as a class property

How to export a function as a class property from a module? Even if modifiers such as public are added, when a class property points to a function within a module, it behaves as though it is private. There are multiple ways to define a property (a, b, c ...

Guide to integrating location-based QR code verification

Currently, I am developing an Angular application where I am utilizing an npm package to generate QR codes. One of my main requirements is to incorporate location-based functionality into the QR code system. For instance, if a user is at a specific hotel a ...

Troubleshooting Next.js and Tailwind CSS Breakpoints: What's causing the

Having trouble with my custom breakpoints. For instance, I attempted the following: <div className="flex flex-row gap-5 mb-5 md:ml-15 sm:ml-15"> ... </div> The margin is not being applied on small and medium screens. Here are the th ...

Extract the variable from the URL path

Looking to retrieve a variable from the URL using Angular. In my routes configuration, I have the following: const routes: Routes = [ { path: ':page', component: BlogComponent} ]; Additionally, in my blog component's constructor, I have ...

Challenges Experienced by AoT in Live Operations

So in my project, I have various components and services included where necessary. To ensure their accessibility, I made sure to declare all the services as private within the constructor. Here's an example: constructor(private myService: MyService) ...

Webpack encountering issues with loading dependencies within dependencies

When I try to run webpack, it seems that the compiler is having trouble loading my app.module from within main.ts. Without using webpack, my application can find all modules correctly, but with Webpack, it's failing. This is my webpack configuration: ...

Node.js serves an Angular application without the need for additional JavaScript scripts

After developing an Angular application with a node.js server, I encountered an issue where the browser displayed the HTML code served by the server as text instead of rendering the web page correctly. This problem arose when I built the Angular project in ...

Using Node.js to efficiently post JSON data in bulk through an API

I am working on a project that involves using Angular2 for the frontend and Nodejs API with 'mssql' NPM package to interact with a Microsoft SQL Server. Everything is functioning as expected, but I'm stuck on one specific task. My challeng ...

Is it possible to switch between mat-checkbox and mat-radio-button within an Angular reactive form?

As I develop a quiz application, I face the challenge of dynamically switching between mat-checkbox and mat-radio-button based on the number of answers for each question. For instance, Question #1 is a single choice question and utilizes mat-radio-button, ...

The promise is unexpectedly fulfilled ahead of schedule without returning the expected value from an AXIOS call

My current challenge involves making a request to a service that rapidly generates multiple strings. The problem lies in returning a promise from this service, as I lack control over the string-generation process. It is crucial for me to return a promise ...

I am looking to refund the sum

I need assistance with returning an amount from a specific function. I have created a function called getWalletTotalAmont() getWalletTotalAmont() { let amount = 0; this.http.post<any>(`${this.generalService.apiBaseUrl}api/wallet/getWalletTotal ...

Dealing with null-safe operators issues has been a challenge for me, especially while working on my Mac using

Hey everyone! I'm encountering errors when using null sage operators in TypeScript. Can someone help me figure out how to solve this issue? By the way, I'm working on Visual Studio Code for Mac. https://i.stack.imgur.com/huCns.png ...

Commitments, the Angular2 framework, and boundary

My Angular2 component is trying to obtain an ID from another service that returns a promise. To ensure that I receive the data before proceeding, I must await the Promise. Here's a snippet of what the component code looks like: export class AddTodoCo ...

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

Deployment failure of AWS CDK caused by Error: Lambda Function Invalid

I'm in the process of integrating a Lambda authorizer into my REST API using AWS CDK. const api = new apigw.RestApi(this, 'apiname', { defaultCorsPreflightOptions: { allowOrigins: apigw.Cors.ALL_ORIGINS } }); const authorizerFuncti ...

The Cordova InAppBrowser plugin has not been properly set up

After running cordova plugin list, I noticed that the InAppBrowser plugin is listed. However, when I try to run my code on an android device, I receive this message in the console via Chrome Remote Debugger: Native: InAppBrowser is not installed or you ar ...

What steps should I take in order to correctly implement the onChange event and retrieve the event.target.value in my

Incorporating useForm, yupResolver, and Yup for validation caused issues with the previously functioning handleChange function. The value variable doesn't log anything when console.logged, indicating a disconnect with the input field content. Addition ...

Angular 8 is facing an issue where classes defined dynamically in the 'host' property of a directive are not being properly applied to the parent template

In my Angular 8 application, I am working on implementing sorting using the ng-bootstrap table. I referred to the example available at . In the sample, when I hover over the table header, it changes to a hand pointer with a highlighted class applied as sho ...

What does the (ERR! code ENOLOCAL npm ERR!) signify? Installation failed due to an error

When attempting to update the latest version of npm, I encountered the following error message: G:\>npm i -g npm ERR! code ENOLOCAL npm ERR! Could not install from "" as it does not contain a package.json file. npm ERR! A complete log of ...