當使用帶有屬性 "Style "的動態類時。包括例如 item.Style="color: red"
它作業正常。
但是Visual Studio代碼拋出了錯誤} expectedcss(css-rcurlyexpected)或類似的錯誤。
結果是正確的,但設計者卻不作業。
在我的例子中,標簽結果是 "紅色",但如何避免語法錯誤?
錯誤。ERROR 錯誤。無法找到一個支持'color.'的不同物件。#DFFDD00;'
uj5u.com熱心網友回復:
ngStyle需要key value作為object。在這種情況下,就需要一個字典。試試我的風格字串到字典決議器。
你可以像默認的css一樣使用它,并使用所有已知的基本CSS語法。
item.Style的例子
background-color:blue;font-size: 22px;color:red;
Angular
<div [ngStyle]="setStyle(item.Style)" >Hello World</div>
TypeScript
private setStyle(value: string): unknown {
console.log(value);
if (value == "") return null;
//示例:value = "background-color:blue"。
var properties = value.split(";");
var keyValuePairs = {};
properties.forEach(o => {
var key = String(o.split(":")[0]).trim()。
var value = String(o.split(":")[1]).trim()。
如果(key.length > 0){
keyValuePairs[key] = value。
}
})
console.log("keyValuePairs: " JSON.stringify(keyValuePairs))。
回傳keyValuePairs。
}
結果
uj5u.com熱心網友回復:
Update: 你可以使用pipe和attr.style系結來實作這一點。
(這也將在你的整個應用程式中得到很好的擴展):
更新:你可以使用pipe和attr.style系結來實作這一點
- 創建一個pipe作為消毒器 。
import { Pipe, PipeTransform } from '@angular/core'。
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser'/span>;
@Pipe({
name: 'safe'。
})
export class SafePipe 實作PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}。
public transform(value: any, type: string) 。SafeHtml | SafeStyle | SafeScript title class_">SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html'/span>: return this.sanitizer.bypassSecurityTrustHtml(value)。
case 'style': return this.sanitizer.bypassSecurityTrustStyle(value)。
case 'script'。return this.sanitizer.bypassSecurityTrustScript(value)。
case 'url'。return this.sanitizer.bypassSecurityTrustUrl(value)。
case ' resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value)。
default: throw new Error(`Invalid safe type specified: ${type}`)。)
}
}
- 在你的模塊中注冊管道 。
@NgModule({
declarations。[SafePipe]。
})
export class AppModule {}。
- 到處使用它...
app.component.html
<p [attr. style]="key.Style | safe:'style'">{{key.Style}}</p>/span>
app.component.ts
export class AppComponent {
key = {Style: "background-color:blue;font-size: 22px;color:red;"}。
}
結果:
演示。https://stackblitz.com/edit/angular-playground-iodcgy?file=app/app.component.ts
參考資料:
[ngStyle]的值必須是key-value pairs或回傳key-value pairs的運算式。
你可以同時使用style和[ngStyle]。然后Angular會將它們合并,例如:
key = {Style: { 'font-size': '18px' }}。
<p style="color: red" [ngStyle]="key. Style"></p>。
結果:
<p style="color: red; font-size: 18px;"></p>>
演示。https://stackblitz.com/edit/angular-playground-jd2g2t?file=app/app.component.html
uj5u.com熱心網友回復:
這應該可以解決這個問題:
這應該可以解決這個問題。
[ngStyle]="'color: #000000; ' key.Style"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/319141.html
標籤:




