在 Angular4 中, View (.html) 上的属性绑定(bind) 从逻辑文件 (.ts) 中获取值
这在代码中运行良好:
<img [src]="sourceValue">
这在代码中也很有效:
<button [disabled]="isDisabled">
为什么这不起作用?
<p [style]="paragraphStyle"> This is a paragraph.</p>
abc.component.ts
isDisabled:boolean = true;
sourceValue:string = "./assets/hermione.jpg";
paragraphStyle:string = "background:red; color:yellow";
我知道 ngStyles 和 ngClass 的用法,我只是想问一下为什么在上述情况下属性绑定(bind)不起作用。如果从 .ts 文件中获取值并添加到段落中“style”属性前面的 html 片段中,它最终就是一个简单的“内联 CSS 样式”。
最佳答案
这是因为安全措施:
@Angular docs
强>
Angular 定义了以下安全上下文:
- HTML 在将值解释为 HTML 时使用,例如,当
绑定(bind)到 innerHtml。
- 将 CSS 绑定(bind)到样式属性时使用样式。
URL 用于 URL 属性,例如
<a href>.
资源 URL 是将作为代码加载和执行的 URL, 例如,在
<script src>
中.
解决方法是使用 bypassSecurityTrustStyle()
预先清理值- 绕过安全性并相信给定值是安全样式值 (CSS)。
WARNING: calling this method with untrusted user data exposes your application to XSS security risks!
组件:
import { Component, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
paragraphStyle;
constructor(private _sanitizer: DomSanitizer){
this.paragraphStyle=this._sanitizer.bypassSecurityTrustStyle("background-color:red");
}
HTML
<p [style]="paragraphStyle"> This is a paragraph.</p>
注意:
For style property name use dash-case. For example, font-weight ,background-color
关于javascript - 在样式属性上使用它时,Angular4 中的这个属性绑定(bind)有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52349308/