Separating HTML content and text from a JSON response for versatile use within various sections of an Angular 2 application using Typescript

Hello there! I am currently utilizing Angular 2 on the frontend with a WordPress REST API backend. I'm receiving a JSON response from the service, however, the WP rest API sends the content with HTML tags and images embedded. I'm having trouble separating this content to use it in my HTML format. I would like the image and text to be displayed in different sections, and also remove the

tag from the content.

Here is an example of the service:

@Injectable()
export class VtkraHomeService {
    private url = 'http://myapplication.com/wp-json/wp/v2/posts';
    private headers = new Headers({'Content-Type': 'application/json'});
    constructor (private http : Http){

    }

    getFeeds(){
        return this.http
        .get(this.url)
        //.then( (res) => res.json);
        .map((res: Response) => res.json());
    }

And here is an example component:

export class HomeComponent implements OnInit { 

  homefeed: any;
  showLoader = false;

  constructor( private VtkraHomeService: VtkraHomeService ) {  }

getHomeFeeds(){
  this.showLoader = true;
  this.VtkraHomeService
  .getFeeds()
  .subscribe(data => {
    this.homefeed = data;
    console.log(this.homefeed);
    this.showLoader = false;
  });
}



  ngOnInit(){
    this.getHomeFeeds()
  }

}

My issue lies in the JSON response structure which looks something like this:

    [
       {
          id: 15953,
          date: '2016-10-22T07:55:34',
          title: {
                   rendered: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum',
                   protected: false
                 },
          content: {
                    rendered: '<p><img src="https://www.w3schools.com/css/paris.jpg" alt="w3c" />Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled ...                    
                    },
           link: 'htts://www.w3schools.com/css/paris',
           type: 'post',
           author: 1
       },
{
   // More items...
}
    ];

I aim to extract the HTML and text separately from the "content (rendered)" field.

content: {
           rendered: '<p><img src="https://www.w3schools.com/css/paris.jpg" alt="w3c" />Lorem Ipsum is simply dummy text of the printing....
           protected: false
         },

The desired HTML format for displaying the content should look like this:

<md-list class="home-feed-list">
  <div *ngFor="let item of homefeed">
  <md-list-item routerLink="/Story">
  <img md-list-avatar src="item.content.rendered(image url)" alt="" class="list-avatar">
  <h4>{{item.title.rendered}}</h4>
<p>{{item.content.rendered(remaining text)}}</p>
  </md-list-item>
  <md-divider></md-divider>
  </div>
</md-list>

If anyone can provide guidance on how to achieve this properly, I would greatly appreciate it as I am still learning about Angular 2 and Typescript.

Answer №1

If you want to extract specific information from a rendered string, you can utilize the DOM API to create an object and fetch the necessary data. This process can be done in your view-model after receiving the data from a service, allowing you to structure your model accordingly (such as creating a homefeed with objects containing images and text).

Below is a straightforward example:

var contentRendered = '<p><img src="https://www.w3schools.com/css/paris.jpg" alt="w3c" />Lorem Ipsum is simply dummy text of the printing and typesetting industry...';

// Convert rendered text into a DOM object
var template = document.createElement("template");
template.innerHTML = contentRendered;

// Use DOM API to retrieve necessary data
var imgPart = template.content.firstChild.querySelector("img");
var text = template.content.firstChild.innerText;

console.log(imgPart);
console.log(text);

Alternatively, you can implement this functionality in custom AngularJS filters, adapting the rendering process accordingly. Even if I'm not well-versed in AngularJS, resources like this link suggest that such techniques are feasible.

I hope this guidance proves useful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing scrapy and python to gather information on attractions from Tripadvisor

Struggling to extract the names and addresses of attractions from TripAdvisor using web scraping. The suspicion is that there might be an issue with how product.css(...) is written (possibly related to jsons?). Seeking guidance on correcting the code in o ...

The term 'Pick' is typically used to identify a specific type, however, in this particular situation, it appears to be functioning as a value while attempting to expand the Pick

I'm attempting to selectively expose certain properties from an ancestor class on my descendant class. My approach involves using the Pick utility in TypeScript. export class Base { public a; public b; public c; } export class PartialDes ...

Turning PHP into JSON with Nested Arrays

I am trying to convert a PHP variable into a JSON string. In my PHP code, I have defined variables for username, password, name, email, and groups, and then used the compact function to create an array of these variables. When I encode this array using jso ...

Can you provide a guide on how to retrieve an HTML file using JSON?

There is a problem with fetching files in different formats. Specifically, I want to retrieve an HTML file that needs to be embedded in an iFrame. Currently, my AJAX request only retrieves SWF files. Is there a way to call and fetch the HTML file instead ...

Retrieving specific properties from a JSON object and logging them

I am attempting to access JSON Object properties directly and log them using the following function : loadProcesses(filter?){ this._postService.getAllProcess(filter) .subscribe( res=> { this.processListe = res; // console.log(this.p ...

What is the method for including a TabIndex property in a JSON file?

I discussed the integration of HTML fields within a JSON file and highlighted how to utilize the TabIndex property effectively in JSON files. ...

What are the steps to enable generators support in TypeScript 1.6 using Visual Studio Code?

I have been working with ES6 in Visual Studio Code for some time now, but when I attempt to transition to TypeScript, I encounter errors like: Generators are only available when targeting ECMAScript 6 Even though my tsconfig.json file specifies the ES6 ...

What is the most effective way to split time into two separate parts?

Suppose a user enters the time as 12:34 and we need to split it into two different parts to save it in an array like [12, 34]. How can this be achieved using Angular? I attempted to split them but my solutions were unsuccessful! I am currently utilizing & ...

Ways to assign a boolean value to HTML using Angular?

Can someone help me set the initial value of showProduct to false for the app-product HTML selector? showProduct:boolean = false; <button (click)="showProduct=!showProduct">Show Product</button> <div *ngIf="!showProduct"> <app-p ...

Angular: Simple Way to Apply a Class to Parent Component upon Clicking a Child Element

Here is some HTML code: <div class="parent"> // This is the parent element <div class="child" (click)="addClassToParent()"></div>// This is the child element </div> How can I use Angular to dynam ...

What is the most optimal JSON encoding format?

I'm working on an Android project and I need to utilize PHP and JSON. However, I am not well-versed in these technologies. My confusion lies in determining the most effective JSON format to use. The majority of examples I have encountered demonstrate ...

Updating templates using Angular 2 observables for change detection

Looking to optimize performance, I am exploring the implementation of manual change detection on my components. The app structure is as follows: App -> Book(s) -> Page(s) In the AppComponent, I subscribe to an observable and then utilize the "markForChec ...

Guide on displaying JSON data from a server on a webpage using Google Charts in real-time

Although I am not a JavaScript developer or an expert in AJAX, I consider myself a novice desktop developer. I would greatly appreciate it if you could guide me on how to connect an MCU that returns JSON data to a web page using Google gauge, running on th ...

Can I keep using ng-repeat multiple times in my code?

Working on a AngularJS application that involves handling a complex JSON file with multiple nested arrays and objects. My query is: Is it appropriate to use ng-repeat repeatedly for accessing the data from the JSON? <div ng-repeat="parent in parents"&g ...

Encountering issues when attempting to set up graphqlExpress due to type

This is my first experience using GraphQL with Express. I have created a schema: import { makeExecutableSchema } from "graphql-tools"; import { interfaces } from "inversify"; const schema = ` type Feature { id: Int! name: String ...

JavaScript and JSON interchangeably, the first AJAX response should be rewritten by the second response

I am facing an issue with my code: I have two ajax calls being made on window.load, and it seems like the response from the second AJAX call is overwriting the response from the first one before my function can process it. I'm not sure where I'm ...

There was total silence from the volleyball players

I've gone through several questions on stackoverflow, but I'm still unable to receive a response from the server using volley. The error inside onErrorRespose() is: com.android.volley.ParseError: org.json.JSONException: Value <br of type java ...

Using ngClass with template literals to dynamically alter its value

Is there a way to dynamically change the classes applied to a div using variables in Angular? In this scenario, I am attempting to modify a class based on the value of a string variable called color by using string interpolation. However, this approach i ...

What is the best way to verify that all elements within an object are 'false' except for one that is 'true'?

I am working with an object that has multiple boolean fields: type SomeObject = { A: boolean B: boolean C: boolean .... } Is there a simple and efficient method to determine if all other fields (except for a specified one) are set to false? We co ...

How can I best access the object being exposed on the webpage using <script type="text/json" id="myJSON">?

In our current project, we are successfully using AMD modules to organize and structure our code. One idea I have is to create an AMD module that accesses a script tag using a jQuery ID selector and then parses the content into JSON format. Here's an ...