0

I want to show an alert when the user selects the checkbox.We have created alert service as a shared component.Because every module is using that.

My code is like:

     if(this.checkboxvalue)
      {
        this.alertservice.error('Hello again! This is how we add line breaks to an alert box!')
      }

I want to show the alert like

Hello again! This is how we add
line breaks to an alert box!

But it displays in a single line.

I tried \n, \\n ,<br\>

But nothing seems to work.

Can anyone help me with this?

Thanks in advance :)

codebuff
  • 93
  • 3
  • 15
  • according to that tryit it works with '\n'. Would you please add the code of this.alertservice.error(...)? – WorksLikeACharm Feb 06 '20 at 13:56
  • https://www.w3schools.com/js/tryit.asp?filename=tryjs_alert2 – WorksLikeACharm Feb 06 '20 at 13:56
  • @WorksLikeACharm I show it in a .ts file.I will add the code of alertservice.error. It is not like a browser alert.This alertservice is the one which is custom alert – codebuff Feb 06 '20 at 13:58
  • I see the error-function now, but how do you consume the subject.next?/how do you show the alert? – WorksLikeACharm Feb 06 '20 at 14:02
  • Actually the above code is written as a service.I am using observable in this service and subscriber at another component – codebuff Feb 06 '20 at 14:13
  • Do you use any library for your alerts? – pzaenger Feb 06 '20 at 14:22
  • If your `alertservice` is injecting the string as HTML, you need a line break tag, which is `
    ` (or `
    `), not `
    ` as you indicate in what you tried. That backslash before the `>` would render the tag ineffective. If the `alertservice` is injecting it as text, you could try `\r\n`.
    – MikeJ Feb 07 '20 at 05:50

3 Answers3

0

User preformatted strings:

const msg = `
aaa
bbb
`;
alert(msg);
Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47
0

What you need is <br/> and not <br\>:

message = "Hello again! This is how we add<br/>line breaks to an alert box!"

It worked for me. Please let me know if you need a stackblitz.

Meziane
  • 1,586
  • 1
  • 12
  • 22
0

It seems that you try to output your error like this in your template:

{myError}

But angular sanitizes the text of myError in {myError} for security reasons. Read more here: https://angular.io/guide/security#sanitization-and-security-contexts

WorksLikeACharm
  • 384
  • 1
  • 6
  • 14