Home > Blockchain >  Print an array from a function inside Angular HTML
Print an array from a function inside Angular HTML

Time:03-03

I'm doing an app where I print some cars (I receive them from the database) and in one column I have one string with multiple tags that are divided by commas, I made a function to receive that as an array of words and then print each word for make tags, but I don't really know how to call the function or how to do it because it's repeating multiple times when it shouldn't do that.

<!-- Category Card -->
<div *ngFor="let car of cars" >
  <div  id="tags">
    {{separar(car?.tags)}}
  </div>
</div>

Then the code of the function "separar":

public separar(string) {
  var palabras = [];
  palabras = string.split(",");
  for (var i = 0 ; i < palabras.length ; i  ) {
    document.getElementById("tags").innerHTML  =
      ("<span class='card-detail-badge'>"   palabras[i]   "</span>");
  }
}

I'm getting this:

enter image description here

and it should only print 3 times those tags.

Probably is a mistake very easy but Im new to angular and my teacher doesn't know why it doesn't work. :(

CodePudding user response:

Try returning the HTML string from the template function instead.

Also, avoid common (sometimes "reserved") words for variables i.e use tagListStr instead of string.

public separar(tagListStr) {
  return tagListStr
    .split(",")
    .map(tag => `<span class='card-detail-badge'>${tag}</span>`)
    .join('');
}

CodePudding user response:

Use ngFor to do it "the Angular way"

  • Related