Search code examples
javascripthtmlangulartypescripttooltip

How to pass UTF-8 Arrow → form typescript to html and display it?


In html I have a div with a tooltip binded to a function. Something like this:

<div *ngFor="let user of users">     
    <div class="myClass" [matTooltip]="user.name + '&#013;' + getUserPhones(user.Id)" matTooltipClass="tooltip-large">{{ user.fullName }}</div>
</div>

This code here: [matTooltip]="user.name + ' ' + getUserPhones(user.Id)" it is generating a tooltip witch will look like: "UserName

--> User Phone 1

--> User Phone 2"

Typescript Code:

public getUserPhones(userId: string): string {
  const currentUser = this.users.find((user) => user.userId === userId);
  const userPhonesArray = viewArr.phoneNumbers; 
  const userPhonesDiplayText = '';

  if (userPhonesArray .length <= 0) {
    return '';
  } else {
  for (let i = 0; i < userPhonesArray.length; i++) {
    userPhonesDiplayText +=  '&rarr;' + userPhonesArray[i] + '&#013;' ;
     return userPhonesDiplayText ;
   }
}

}

What I am trying to do: In case a user has more than 1 phone numbers I want to display an arrow with the phone in new line

The issue is that the codes passed to html do not change to arrow('→') and new line (' '). I am getting something like: Username → Phone1 → Phone2

How can I pass the string from typescript to html and get the arrow and the empty line? Is it possible?


Solution

  • You can't directly pass HTML character entities into the string, as they will be displayed as strings.

    What you can is embed relevant Unicode characters in the string itself by using it's codepoint.

    The syntax is \uXXXX or \u{XXXX}. The codepoint of right arrow is 2192, so you should be able to achieve it by adding \u2192 to the string. Likewise, for line breaks, you can simply add \r\n to the string.

    So you would end up with something like \u2192 123456789 \r\n \u2192 987654321. This should correctly display both arrows and line breaks in the tooltip. Note that by default material tooltips don't respect inserted linebreaks, so you'll have to add custom styling to them, namely white-space: pre-line;.

    You can do this by defining your class in global styles.scss files, e.g.

    .multiline-tooltip {
      white-space: pre-line;
    }
    

    And applying that class to your tooltip, e.g.:

    [matTooltip]="tooltipText"
    [matTooltipPosition]="position.value!"
    [matTooltipClass]="'multiline-tooltip'"