javascript - 在样式属性上使用它时,Angular4 中的这个属性绑定(bind)有什么问题?

标签 javascript angular property-binding

在 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";

我知道 ngStylesngClass 的用法,我只是想问一下为什么在上述情况下属性绑定(bind)不起作用。如果从 .ts 文件中获取值并添加到段落中“style”属性前面的 html 片段中,它最终就是一个简单的“内联 CSS 样式”。

最佳答案

这是因为安全措施:

@Angular docs
Angular 定义了以下安全上下文:

  • HTML 在将值解释为 HTML 时使用,例如,当
    绑定(bind)到 innerHtml。
  • 将 CSS 绑定(bind)到样式属性时使用样式。
  • URL 用于 URL 属性,例如 <a href>.

  • 资源 URL 是将作为代码加载和执行的 URL, 例如,在 <script src> 中.

解决方法是使用 bypassSecurityTrustStyle() 预先清理值- 绕过安全性并相信给定值是安全样式值 ​​(CSS)。

@Angular docs

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

Live Demo

关于javascript - 在样式属性上使用它时,Angular4 中的这个属性绑定(bind)有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52349308/

相关文章:

javascript - 指向外部 URL 的 Angular 2 链接被视为路由的相对路径

javascript - Cordova 3.4.0 : File Api GetFile Abort Error

angular - "Expected operands to be a string or number type" Angular

Angular Material 2 卡片可滚动

Birt 中的属性绑定(bind)或查询中的 Javascript

c++ - 属性绑定(bind)导致错误,对象位置在插入时中断

javascript - Meteor:如何在空格键内动态设置数组值

javascript - WebSocket 到本地主机在 Microsoft Edge 上不起作用

javascript - 有没有办法在直播时从 YouTube API 获取通知

angular - 连接为 Meteor 客户端的 Ionic UI 的简单示例?