以棱角分明的方式显示内容丰富的富文本



我的Angular应用程序中有一个与Contentful连接的博客提要。感谢 Contentful JavaScript SDK。

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

我正在尝试显示标题和文本字段。这是我的代码:

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);
});
}
}

和 html:

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

title字段显示良好,因为它只是一个字符串字段,但text字段是富文本并显示 [对象对象]。

事实上,它包含几个对象。似乎对象被分成了几部分。

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

是否有人已经在 Angular 应用程序中显示内容富文本? 有没有特定的方法可以做到这一点?

首先,您必须从终端安装 rich-text-html-renderer:

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

然后,您可以从组件导入它:

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

并使用它,就像这样:

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

最后,从你的html中"调用函数",如下所示:

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

您还可以添加一些选项来自定义富文本,更多信息请点击此处。此外,还应编写类似于内容服务中的_returnHtmlFromRichText函数,以便以后能够重用它。

我创建了一个可以使用 Angular 组件渲染富文本的 Angular 库: https://github.com/kgajera/ngx-contentful-rich-text

为什么要在@contentful/rich-text-html-renderer使用它?如果您需要自定义默认标记,它允许您使用 Angular 组件,而您无法使用documentToHtmlString函数和[innerHTML].

最新更新