0

我有一个返回一些 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);
    }
}

DomSanitizationService 文档

4

1 回答 1

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中的所有示例

于 2016-09-09T20:14:29.397 回答