gpt4 book ai didi

javascript - innerHtml 不适用于 ionic 2 管道,如何操作?

转载 作者:行者123 更新时间:2023-12-03 06:08:44 26 4
gpt4 key购买 nike

我有一个返回一些 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 中你必须使用属性绑定(bind):

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

关于javascript - innerHtml 不适用于 ionic 2 管道,如何操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39417697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com