2017-08-31 38 views
1

我遇到了這個問題。現在Angular - 如何清理簡單打字稿類中的樣式?

WARNING: sanitizing unsafe style value rotate(36.362868584929245deg)translate(91px,67px) (see http://g.co/ng/security#xss).

,一些研製後,我發現我不得不使用DomSanitizer應注入部件,像這樣:

constructor(private sanitizer: DomSanitizer)

我的問題是,我的課需要衛生處理是一個簡單的打字稿類,它不是一個組件。我如何注射殺菌劑?或者以其他方式清理這個值。

以下是相關代碼:

模板:

<div class="transition" *ngFor="let transition of state.transitions" 
    [style.transform]="transition.transformPosition" 
    [style.width.px]="transition.width"></div> 

類:

export class Transition { 
    origin: State; 
    destination: State; 
    conditions: AlphabetSymbol[]; 

    constructor(origin: State, destination: State) { 
    this.origin = origin; 
    this.destination = destination; 
    } 

    get transformPosition() { 
    let x = (this.origin.layoutPosition.x + this.destination.layoutPosition.x)/2, 
     y = (this.origin.layoutPosition.y + this.destination.layoutPosition.y)/2, 
     angle = Math.atan( (this.destination.layoutPosition.y - this.origin.layoutPosition.y) 
         /(this.destination.layoutPosition.x - this.origin.layoutPosition.x)), 
     finalString; 

    x -= this.origin.layoutPosition.x; 
    y -= this.origin.layoutPosition.y; 
    angle *= 180/Math.PI; // Convert to degrees 
    finalString = "rotate(" + angle + "deg)translate(" + x + "px," + y + "px)";   

    return finalString;        
    } 

    get width() { 
    return this.origin.layoutPosition.distanceTo(this.destination.layoutPosition) - 60; 
    } 
} 

僅供參考,如果我回到平原 「改造」 的值,只需翻譯或只是一個旋轉,它接受字符串,但將它們組合標記爲不安全。

回答

0

我設法通過在模板的父組件中定義的函數內包裝不安全的樣式來解決這個問題。

模板

<div class="transition" *ngFor="let transition of state.transitions" 
    [style.transform]="sanitizeStyle(transition.transformPosition)" 
    [style.width.px]="transition.width"></div> 

模板的父(組件)

constructor(private sanitizer: DomSanitizer) 
... 
sanitizeStyle(unsafeStyle: string): SafeStyle { 
    return this.sanitizer.bypassSecurityTrustStyle(unsafeStyle); 
}