这个问题通常出现在 Angular 的版本 9 以上。原因是 Angular 把 SafeValue 的默认设置从原来的 bypassSecurityTrustHtml
改成了 bypassSecurityTrustHtml
和 bypassSecurityTrustStyle
。因此,在使用 SafeValue 时,必须设置绑定属性 [property]。具体实现方法如下所示:
在自定义管道中导入 SafeValue 类:
import { SafeValue } from '@angular/platform-browser';
在管道中使用 SafeValue:
@Pipe({
name: 'myCustomPipe'
})
export class MyCustomPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(value: string): SafeValue {
// 使用 bypassSecurityTrustHtml 方法可以从字符串创建 SafeValue
return this.sanitizer.bypassSecurityTrustHtml(value);
}
}
在模板中使用管道时,必须绑定属性 [property]:
以上代码中,myHtml
是一个包含 HTML 的字符串,myCustomPipe
是自定义管道的名称。
通过以上设置,就可以正确使用 SafeValue 相关的管道了。