在我的Angular应用程序中,我有一个与Contentful相关的博客feed。多亏了内容丰富的javascript sdk。
我正在尝试显示标题和文本字段。下面是我的代码:
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字段是RichText并显示对象对象。
实际上,它包含几个对象。看起来这个物体被分成了几个部分。
https://www.contentful.com/developers/docs/concepts/rich-text/
是否有人已经在Angular应用程序中显示了Contentful?有没有具体的方法呢?
发布于 2019-12-01 12:38:43
首先,您必须从终端安装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>你也可以添加一些选项来定制你的富文本,更多信息here。此外,您应该在内容服务中编写一个类似于_returnHtmlFromRichText的函数,以便以后能够重用它。
发布于 2020-02-28 23:57:11
我创建了一个可以使用Angular组件呈现富文本的Angular库:https://github.com/kgajera/ngx-contentful-rich-text
为什么要在@contentful/rich-text-html-renderer上使用它呢?如果你需要定制默认的标记,它允许你使用你的角度组件,这是你不能使用documentToHtmlString函数和[innerHTML]完成的。
https://stackoverflow.com/questions/57893367
复制相似问题