如何从json中收到的某些文本提供指向浏览器的超链接?
我正在使用Angular 4调用来自json文件中的对象的数组,它是一个非常基本的博客。问题是,在json我咨询了一个名为" body"在其中加载帖子的主体时,我需要做的是识别该文本中的每个链接,当它被加载到调用它的div中时。
杰森看起来像这样:{"posts": [
{
"id": 1,
"date":"November 10th, 2017",
"time":"3:50PM",
"body": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque
penatibus
et magnis dis parturient montes, nascetur ridiculus mus. Donec quam
felis",
"img": null
},
{
"id": 2,
"date":"November 10th, 2017",
"time":"3:50PM",
"body": "Loremsa. Cum sociis natoque penatibus et magnis dis
parturient montes, nascetur ridiculus mus. Donec quam felis",
"img": null
},
{
"id": 3,
"date":"November 10th, 2017",
"time":"3:50PM",
"body": "http://www.webesite.com Lorem elit. Aenean commodo ligula
eget dolor. Aenean massa.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur
ridiculus mus. Donec quam felis",
"img": "https://scontent.fcnq1-1.fna.fbcdn.net/v/t1.0-9/22491481_680661882130471_2500422036645997028_n.jpg?oh=2e5001e92d201e446e3120204869a434&oe=5A68A19D"
}
]
}
我正在使用* ng这样的div来调用它
<div class="row mt-3">
<div class="col-12 card-inf bg-inf-blue text-white mb-3 px-0" *ngFor="let post of posts">
<div class="card-header-inf">
<div class="row">
<div class="col-6">
<h6>Informatorio</h6>
</div>
<div class="col-6 text-right"><small>{{post.date}} - {{post.time}}
</small></div>
</div>
</div>
<div class="card-body-inf bg-inf-blue pt-0">
<div class="row">
<div class="col-12">{{post.body}}</div>
<div class="col-12 mt-3 img-responsive" *ngIf = "post.img != null">
<img src="{{post.img}}" alt="" class="img-fluid img-thumbnail ">
</div>
</div>
</div>
</div>
</div>
正如你所看到的,在&#34;身体的开始&#34; json的第三个数组中的字段是平面文本中的链接,我需要的是链接在视图中被识别为链接。
答案 0 :(得分:0)
我为你创建了一个working stackblitz。 这里的方法是利用innerHtml并将post.body传递给函数来构建格式化的html。
<div *ngFor="let post of posts">
<div [innerHTML]="parseBody(post.body)">
</div>
</div>
parseBody(body:string) {
// TODO you will need to improve this regex.
return body.replace(/(http.*?\s)/, "<a href=\"$1\">$1</a>")
}