【发布时间】:2018-09-09 13:26:20
【问题描述】:
我有一个 Angular 5 应用程序,它通过 REST API 使用来自 Wordpress 的内容。
我想做的是在 Wordpress 内容编辑器中插入一个组件标签,然后让它出现在应用程序中。
比如我创建了一个简单的组件<app-some-component></app-some-component>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-some-component',
template: `
<h1>I am a component!</h1>
`
})
export class SomeComponent implements OnInit {
constructor() {}
ngOnInit() {}
}
并直接添加到宿主组件模板中进行测试,就可以了。
现在,该主机组件还通过其余 API 从 Wordpress 中提取内容。所以我尝试在 Wordpress 内容编辑器中添加<app-some-component></app-some-component>。
标签“通过”到 Angular 应用程序,我在检查页面时看到 HTML 中的标签。但是组件的内容没有渲染,所以我猜它没有被Angular处理。
我正在使用安全管道来允许组件中包含 HTML,如
<div class="card"
*ngFor="let vid of videolist">
<img class="card-img-top img-fluid"
[src]="vid.better_featured_image.source_url"
alt="Video Thumbnail">
<div class="card-body">
<h4 class="card-title"
[innerHTML]="vid.title.rendered"></h4>
<p class="card-text"
[innerHTML]="vid.content.rendered | safe: 'html'"></p>
</div>
<div class="card-footer">
<a routerLink="/videos/{{vid.id}}">View Video</a>
</div>
</div>
管道的代码是
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({ name: 'safe' })
// see https://medium.com/@swarnakishore/angular-safe-pipe-implementation-to-bypass-domsanitizer-stripping-out-content-c1bf0f1cc36b
// usage: <div [innerHtml]="htmlSnippet | safe: 'html'"></div>
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html':
return this.sanitizer.bypassSecurityTrustHtml(value);
case 'style':
return this.sanitizer.bypassSecurityTrustStyle(value);
case 'script':
return this.sanitizer.bypassSecurityTrustScript(value);
case 'url':
return this.sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl':
return this.sanitizer.bypassSecurityTrustResourceUrl(value);
default:
throw new Error(`Invalid safe type specified: ${type}`);
}
}
}
我需要做什么才能让组件呈现?
【问题讨论】:
标签: javascript wordpress angular wordpress-rest-api angular-pipe