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>
何か案は?
1 つのソリューション
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);
}
}