简体   繁体   中英

String from api response cant display break line, but hard code string can display break line

Good day,

I am using Angular 8 as my frontend, and java api service as my backend.

I need to retrieve some String from backend, and the String will having \n in between, for example: "Instructions:\n1. Key in 122<16 digit \nreload pin># to reload.\n2. Press SEND/CALL from

In my .ts file, I am setting this String value as follow:

this.str = this.apiRes.responseMsg1;
console.log("this.str : " + this.str);

This will give me Instructions:\n1. Key in 122<16 digit \nreload pin># to reload.\n2. Press SEND/CALL Instructions:\n1. Key in 122<16 digit \nreload pin># to reload.\n2. Press SEND/CALL Instructions:\n1. Key in 122<16 digit \nreload pin># to reload.\n2. Press SEND/CALL , thus when I use it to display in html, it will just display as 1 line.

If I hard code this String to a String variable, for example:

this.str = "Instructions:\n1. Key in 122<16 digit \nreload pin># to reload.\n2. Press SEND/CALL from";
console.log("this.str : " + this.str);

It will give me :

Instructions:
1. Key in 122<16 digit 
reload pin># to reload.
2. Press SEND/CALL from 

Which is what I want.

I am not really familiar with Angular, I am trying to find this answer in google, but cant get any related result.

May I know why is this happen? And any way I can display the api message accordingly?

HTML ignores \n line breaks. You basically have two options to fix this:

  1. Replace the line breaks with <br> elements.
  2. Add a line of css white-space: pre-wrap; to your HTML element which is displaying your string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM