0

In an Angular 10 app I have a string that's composed of several template literals passed in from a function:

  getFormattedAddress(addr): string {
    const nameAndAddress = `
    ${addr.name} 
    ${addr.address} 
    ${addr.city}, ${addr.state}  ${addr.postalCode}, ${addr.country}
    `;
    return nameAndAddress;
  }

and used in the template as such:

{{ getFormattedAddress(senderAddress) }}

Everything I read about template string literals says if you split it onto lines like I have it will come back a multiline string. Does this not apply the way I am trying to use it here?

For now, I have used [innerHTML] to do it, like so:

<div [innerHTML]="getFormattedAddress(shipment.senderAddress)"></div>

and modified my function to use <br> tags:

  getFormattedAddress(addr): string {
    const nameAndAddress = `
    ${addr.name} <br>
    ${addr.address} <br>
    ${addr.city}, ${addr.state}  ${addr.postalCode}, ${addr.country}
    `;
    return nameAndAddress;
  }

Is this the only way? Can't I construct a multiline template literal and return it to a template binding?

Steve
  • 14,401
  • 35
  • 125
  • 230
  • Even if the string contains line breaks (`\n` or `\r\n`), they will not translate to line breaks in the browser. A line break in HTML is output as a simple space in the browser. You can use CSS to change that behavior, as shown in [this post](https://stackoverflow.com/q/39325414/1009922). – ConnorsFan Aug 09 '20 at 01:04
  • Yes, I read that. It adds a bunch of space around the PRE tag. Also, according to [this article](https://medium.com/dailyjs/how-to-create-multi-line-string-with-template-literals-in-javascript-a3a140d0b0f6) you can use ES6 template literals to create mutliline strings as I said in my post. – Steve Aug 09 '20 at 15:25

0 Answers0