我想显示带有段落的JSON字符串形式编写的文本。最好的方法是怎么做到的?
这是我的dashboard.component.ts:
export class DashboardComponent implements OnInit {
items: Array<IService>;
blogs: Array<any>;
comment: any;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getAllServices()
.subscribe(
(data: IService[]) => this.items = data,
(err: any) => console.log(err),
() => console.log('All done getting the services.')
);
this.dataService.getAllBlogposts()
.subscribe(
(data: any[]) => this.blogs = data,
(err: any) => console.log(err),
() => console.log('All done getting the blogposts.')
);
this.dataService.saveComment(this.comment)
.subscribe(comment => this.comment.push(this.comment));
}
}
这是我的blogposts.json: 我的想法是将json字符串放在html元素中,以便显示html。有更好的方法吗?
[{
"postName": "Was sind eigentlich diese Observables in Angular?",
"postId": "1",
"postText": "<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
</br> sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
</p>"
}]
这是我显示博客文章的模板:
<div class="row">
<h1>Services</h1>
</div>
<div class="card col-md-3 col-lg-3 justify-content-center float-left"
*ngFor="let item of blogs">
<div class="row justify-content-center">
<div class="card-header">
{{ item.postName }}
</div>
</div>
<div class="row justify-content-center">
<div class="card-body">
<span>{{ 'ID: ' + item.postId }}</span> <br>
<span *ngFor="let el of blogs">
{{ item.postText }} <br />
</span>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-12">
<div class="widget-area no-padding blank">
<div class="status-upload">
<form>
<textarea placeholder="What do you think of my blogpost?" >{{ comment }}</textarea>
<button type="submit" class="btn btn-success green"><i class="fa fa-share"></i> Share</button>
<br>
</form>
</div><!-- Status Upload -->
</div><!-- Widget Area -->
</div>
</div>
</div>
答案 0 :(得分:0)
为了显示换行符,您必须使用innerHTML
指令:
<span *ngFor="let el of blogs" [innerHTML]="el.postText"></span>
Angular将按原样呈现HTML,而不是像简单的字符串那样解释它。