1

I am using Angular 5 and I have the following JSON response from a Rest API call. I was able to get the value of the info key inside a variable in my component. I would like to use the HTML inside my view. However, since it's not a valid HTML, I would like to replace \" with " :

{
  "id": "1234",
  "body": {
  "content": {
    "info": "<p><div class=\"abc\">xyzdef</div><span class=\"egg\"></span></p>"
  }
}

How do I do that? Should I do it in html or typescript?

7
  • 1
    If you parsed the JSON correctly, there is no need to replace anything. Commented Oct 29, 2018 at 7:18
  • Are you referring to angular.fromJson()? Commented Oct 29, 2018 at 7:20
  • Depends on what exactly do you want to do with this string Commented Oct 29, 2018 at 7:21
  • It's basically HTML. So, I want to embed it in the .html file inside a div Commented Oct 29, 2018 at 7:21
  • 1
    When you parse this JSON, the string value of the info property will be <p><div class="abc">xyzdef</div><span class="egg"></span></p>, ready to be put into HTML as it is. Commented Oct 29, 2018 at 7:32

3 Answers 3

2

use .replace("'\'") for this.

"<p><div class=\"abc\">xyzdef</div><span class=\"egg\"></span></p>".replace("'\'")
Sign up to request clarification or add additional context in comments.

Comments

1

Just use [innerHTML]:

<div [innerHTML]="res"></div>

In TypeScript Class:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  ...
  res = "<p><div class=\"abc\">xyzdef</div><span class=\"egg\"></span></p>";
  ...
}

Here's a Sample StackBlitz for your ref.

Comments

1

No need to replace anything it's working properly. component code is

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = "<p><div class=\"abc\">xyzdef</div><span class=\"egg\"></span></p>";
}

html code is

<div [innerHTML]="title"></div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.