Home > Net >  Javascript code number likes by typescript / angular
Javascript code number likes by typescript / angular

Time:07-01

I have some javascript code which I'm trying to add to my component.ts in my angular project.

Here is the code:

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

  // The issue is in the code below:
  for (let area of document.getElementsByClassName("some-area")) {
    area.style.height = 100 / areaNum   "%";
  }
}

The error is:

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

How can I fix this so it work in Angular?

CodePudding user response:

Document.getElementsByClassName returns a live HTMLCollection. MDN link

You can make it into an array using Array.from

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

CodePudding user response:

Use CSS Only, no need for javascript

Why are you updating html from angular functions via javascript. Based on your code you should actually style the div (some-area's parent element) to be display:flex and the children some-area to have flex:1.

Once the style is in place, you can add 1 or 1000 elements and it will always display it right.

The angular / javascript should only be responsible for adding and removing the elements. You must try to avoid such type of style manipulation from javascript at all times.

Requirement

You want to equally space the some-area element inside their container so that their heights are 100% / number of elements.

This can be simply achieved by using CSS Flex-box no need to get javascript involved.

Better Solution

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

  /* Important Style */
  display: flex;
  flex-direction: column;
}

.some-area {
  /* Boilerplate Style */
  background-color:red;
  color:#fff;
  padding:10px;
  
  /* Important Style */
  flex-grow: 1;
}
<div >
  <div >some content</div>
  <div >some content</div>
  <div >some content</div>
  <div >some content</div>
</div>

  • Related