innerHtml 不适用于 ionic 2 管道,怎么办?

innerHtml doesn't work with ionic 2 pipes, how to?

我有一个简单的管道 returns 一些 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);
    }
}

documentation on DomSanitizationService

它不适用于此 html

"<ion-icon name='star'>" + value + "</ion-icon>"

因为 ion-icon 是一个 ionic-angular 组件,它应该通过 angular2 加载而不是仅仅使用 innerHTML.

无论如何,您应该像这样为您的 html 管道使用 DomSanitanizeService:

@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

中的所有示例