Angular 2,将calc()添加为内联样式。使用括号进行不安全插值 [英] Angular 2, Adding calc() as inline style. Unsafe interpolation using parentheses
问题描述
Angular 2 rc3
我正在尝试动态添加 calc()
到模板中的元素。我有类似的东西。
I am trying to dynamically add calc()
to an element in a template. I have something like this.
template : `<div attr.style.width="{{width}}></div>"`
export myClass
{
@Input() myInputObject:any;
private width:string;
ngOnInit() { this.setWidth()}
private setWidth()
{
let percent = myInputObject.percent;
this.width = 'calc(' + percent + '% - 20px)';
}
}
如果我使用括号,则输出如下所示DOM。
If I use the parenthesis the ouput looks like this in the DOM.
< div style =unsafe>< / div>
如果我拿出括号,它就可以了(有点)看起来像这样。
If I take out the parenthesis it works (sort of) It looks like this.
< ; div style =calc10% - 20px>< / div>
这也不起作用。
<div attr.style.width="calc({{width}} - 20px)">
有关如何添加 calc()的任何帮助
非常感谢模板。注意我也尝试用&#40;
和&#41;
替换括号。这又回来了不安全。
Any help on how to add calc()
to the template is much appreciated. Note I also tried replacing the parenthesis with (
and )
. That also came back as "unsafe".
示例:(rc1)
我在我的环境中使用rc3。但我能够在plunker中重现RC1的相同问题。我假设这是一个安全的事情。但必须有一种方法可以将 calc()
添加到样式属性中。也许还有比这更好的方法?
I am using rc3 in my environment. But I was able to reproduce the same issue with RC1 in plunker. I am assuming this is a security thing. But there must be a way to add calc()
to a style attribute. Maybe there is a better way than this?
https://plnkr.co/edit/hmx5dL72teOyBWCOL0Jm?p=preview
推荐答案
计算的样式应为<强>消毒即可。
Calculated styles should be sanitized.
以下是适合您的解决方案:
Here is the solution for you:
import {DomSanitizationService} from '@angular/platform-browser';
@Component({
selector: 'my-app'
template: `
<div [style.width]="width">
<h2>Hello {{name}}</h2>
</div>
`
})
export class App {
private width:string;
constructor(sanitizer: DomSanitizationService) {
this.name = 'World'
this.width = sanitizer.bypassSecurityTrustStyle("calc(10% - 20px)");
}
}
这篇关于Angular 2,将calc()添加为内联样式。使用括号进行不安全插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!