我有一个简单的管道返回一些html
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'rating',
pure: false
})
export class RatingPipe implements PipeTransform {
transform(value: any): string {
let stars = "<ion-icon name='star'>" + value + "</ion-icon>";
return stars;
}
}
问题是当我使用它时,我什么都没得到
// this works fine
<p><span innerHtml="{{'<h1>some text</h1>'}}"></span></p>
// if I add a pipe, it doesn't work
<p><span innerHtml="{{variableFromControler | rating}}"></span></p>
// if I add a pipe, it doesn't work
<p><span [innerHtml]="variableFromControler | rating"></span></p>
任何想法?
一种解决方案
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizationService } from '@angular/platform-browser'; // to become DomSanitizer
@Pipe({
name: 'rating',
pure: false
})
export class RatingPipe implements PipeTransform {
sanitizer: any;
constructor(private domSanitizationService: DomSanitizationService) {
this.sanitizer = domSanitizationService;
}
transform(value: any): string {
value = parseInt(value);
let stars = '';
for(let i = 1; i <= 5; i++) {
stars += i <= value ? "<ion-icon class='ion-ios-star'></ion-icon>" : "<ion-icon class='ion-ios-star-outline'></ion-icon>";
}
return this.sanitizer.bypassSecurityTrustHtml(stars);
}
}
答案 0 :(得分:1)
它不适用于此html
"<ion-icon name='star'>" + value + "</ion-icon>"
因为ion-icon
是一个离子角度组件,它应该通过angular2加载而不是仅使用innerHTML
。
无论如何,您应该使用DomSanitanizeService作为您的html管道:
@Pipe({
name: 'rating',
pure: false
})
export class RatingPipe implements PipeTransform {
constructor(private domSanitizer: DomSanitizationService){}
transform(value: any): string {
let stars = "<div>" + value + "</div>";
return this.domSanitizer.bypassSecurityTrustHtml(stars);
}
}
在你的html中你必须使用属性绑定:
<span [innerHtml]="text | rating"></span>
我会为您的案例利用自定义图标包装器:
@Component({
selector: 'ion-rating-icon',
template: '<ion-icon name="star">{{rating}}</ion-icon>'
})
class RatingIconComponent {
@Input() rating;
}
然后使用它:
<ion-rating-icon [rating]="text"></ion-rating-icon>
查看 Plunker
中的所有示例