4

I have a blog feed in my Angular App connected with Contentful. Thanks to the Contentful javascript sdk.

https://www.contentful.com/developers/docs/javascript/tutorials/using-contentful-in-an-angular-project/

I'm trying to display the Title and the Text field. Here is my code:

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs';
import {ContentfulService} from '../../services/contentful/contentful.service';
import { Entry } from 'contentful';

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {
  private posts: Entry<any>[] = [];

  constructor(private postService: ContentfulService) {}

  ngOnInit() {
    this.postService.getPosts()
      .then(posts => {
        this.posts = posts;
        console.log(this.posts);
      });
  }
}

And the html:

<div *ngFor="let post of posts">
    <a href="#">{{ post.fields.title }}</a>
    <div>{{ post.fields.text }}</div>
</div>

The title field is displayed well because it is just a string field but the text field is RichText and display [object Object].

Indeed it contain several object. It seems like the Object is divided in several pieces.

https://www.contentful.com/developers/docs/concepts/rich-text/

Does somebody have already display Contentful RichText in an Angular App ? Is there a specific way to do it?

Kevin
  • 4,823
  • 6
  • 36
  • 70

2 Answers2

8

First, you must install rich-text-html-renderer from your terminal:

npm install @contentful/rich-text-html-renderer

Then, you can import it from your Component:

import { documentToHtmlString } from '@contentful/rich-text-html-renderer';

and use it, simply like that:

_returnHtmlFromRichText(richText) {
    if (richText === undefined || richText === null || richText.nodeType !== 'document') {
      return '<p>Error</p>';
    }
    return documentToHtmlString(richText);
}

Finally, 'call the function' from your html like so:

<div [innerHtml]="_returnHtmlFromRichText(post.fields.text)">
</div>

You can also add some options to customise your rich text, more information here. Also, you should code a function similar to _returnHtmlFromRichText in your Contentful service to be able to reuse it later.

Rekoc
  • 438
  • 6
  • 17
4

I created an Angular library that can render rich text using Angular components: https://github.com/kgajera/ngx-contentful-rich-text

Why use this over @contentful/rich-text-html-renderer? If you need to customize the default mark-up, it allows you to use your Angular components which you can't do using the documentToHtmlString function and [innerHTML].

Kishan
  • 915
  • 6
  • 12