Angular - for loop to generate data for a tag cloud

48 Views Asked by At

I am new to angular. I am trying to generate a tag cloud. I can generate the tag cloud but however the list of words I receive is dynamic from an api response. So I wanted to create a for loop that generates the source for tag cloud based on the no. of words received from the api call.

In the mentioned code 'keywords' & 'count' is where I store the api response.

In data: CloudData I have hardcoded the data for 6 values but it should be generating based up on the api. In data: CloudData[] = [ ..// ]

Please help me on this.

app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { CloudData, CloudOptions, TagCloudComponent } from 'angular-tag-cloud-module';


@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, TagCloudComponent],
  styleUrl: './app.component.css',
  templateUrl: './app.component.html' 
})

export class AppComponent {
  title = 'angularapp';
  options: CloudOptions = {

    width: 1500,
   
    height: 450,
    overflow: true,
};
  
 keywords = ['A', 'P', 'R', 'CL', 'U','S', 'DI', 'DE', 'SC', 'K', 'S', 'L', 'PI', 'ER', 'RDER', 'RROR', 'SAN', 'UND', 'KIN', 'IMA']
 count =  ['10', '11', '7', '13', '5', '1','30', '1', '10','12','9', '14', '10', '14', '12', '17', '12', '1', '18', '7']


 data: CloudData[] =
[
      {text:  this.keywords[0], weight: Number(this.count[0]),tooltip: this.count[0]},
      {text:  this.keywords[1], weight: Number(this.count[1]),tooltip: this.count[1]},
      {text:  this.keywords[2], weight: Number(this.count[2]),tooltip: this.count[2]},
      {text:  this.keywords[3], weight: Number(this.count[3]),tooltip: this.count[3]},
      {text:  this.keywords[4], weight: Number(this.count[4]),tooltip: this.count[4]},
      {text:  this.keywords[5], weight: Number(this.count[5]), tooltip: this.count[5]},
];
}
app.module.ts

import { NgModule } from '@angular/core';
import { TagCloudComponent } from 'angular-tag-cloud-module';

@NgModule({
  imports: [
    TagCloudComponent
  ]
})
export class AppModule { }
app.component.html
<div class="content">
        <angular-tag-cloud
          [data]="data"
          [width]="options.width"
          [height]="options.height"
          [overflow]="options.overflow"
          style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;"
          style="align-self: center;"
          >
        </angular-tag-cloud>
</div>
1

There are 1 best solutions below

0
On

Well, simple. Try to refactory the code in app.component.ts file this way:

data: CloudData[] = [];
for (let i = 0; i < keywords.length; i++) {
data.push( {text:  this.keywords[i], weight: Number(this.count[i]),tooltip: this.count[i]});

Be sure that keywords and count arrays had the same length, or, better, use a dictionary (Map), but this other discussion