Javascript Angular4中的此属性绑定在style属性上使用时有什么问题?
在Angular4中,视图(.html)上的属性绑定从逻辑文件(.ts)中获取值 这在代码中非常有效:Javascript Angular4中的此属性绑定在style属性上使用时有什么问题?,javascript,angular,property-binding,Javascript,Angular,Property Binding,在Angular4中,视图(.html)上的属性绑定从逻辑文件(.ts)中获取值 这在代码中非常有效: <img [src]="sourceValue"> <button [disabled]="isDisabled"> 我知道ngStyles和ngClass的用法,我只想问一下为什么在上述情况下属性绑定不起作用。最后,如果值取自.ts文件并添加到段落中“style”属性前面的html代码段中,那么它就是一个简单的“内联CSS样式”。我认为您可以这样做,但您必须这
<img [src]="sourceValue">
<button [disabled]="isDisabled">
我知道ngStyles和ngClass的用法,我只想问一下为什么在上述情况下属性绑定不起作用。最后,如果值取自.ts文件并添加到段落中“style”属性前面的html代码段中,那么它就是一个简单的“内联CSS样式”。我认为您可以这样做,但您必须这样做:
[style.background]=“红色”
这是因为安全措施:
Angular定义了以下安全上下文:
- 将值解释为HTML时使用HTML,例如
绑定到innerHtml。 - 将CSS绑定到样式属性时使用样式。
- URL用于URL属性,例如
警告:使用不受信任的用户数据调用此方法会暴露您的错误 应用到XSS安全风险 组件:
HTMLimport { 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"); }
<p [style]="paragraphStyle"> This is a paragraph.</p>
注意:这是一个段落
对于样式属性名称,请使用破折号大小写。 例如,字体大小、背景颜色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"); }
谢谢,但问题又来了,为什么不从.ts中提取值,然后像视图部件上的其他案例一样进行替换呢?这将是一个“简单的内联样式”。不知道,但我知道它并没有真正按照您想要的方式工作。它必须与样式规则以及它们如何在渲染器中应用它们有关。最好只使用ngStyles或ngClass。顺便说一句,您应该更喜欢使用类,因为内联样式不会在浏览器中缓存。使用此方法,您实际上可以从ts中提取值,您只需要用属性名替换“red”。像这样:
您是否收到任何错误或警告?从技术上讲,Angular将名称与指令输入、指令输入数组中列出的属性名称之一或用@input()修饰的属性相匹配。此类输入映射到指令自身的属性。“-->”如果名称与已知指令或元素的属性不匹配,Angular将报告“未知指令”错误@NerijusPamedytis看一下我的答案,以获得一个清晰的画面:)您在这里做的事情是您不应该做的,组件中的TypeScript文件用于在html视图和服务之间编组数据,html文件用于表示。如果您的TypeScript中有图像名称和样式,那么您正在错误地考虑分离关注点。[style.background]=“redVariable”
<p [style]="paragraphStyle"> This is a paragraph.</p>