2017-06-09 34 views
3

我一個簡單的animation library工作在我的用戶可以使用屬性綁定修改我的成分,到目前爲止,我一直在做下列申請自己的選擇:角ngStyle多個款式

<div [style.background]="color" [style.width.px]="width" [style.height.px]="height"></div> 

但對於未來增加我想改變這整個惹[ngStyle]="styleObject"簡化添加更多的特性,我想實現這個像這樣:

@Input() width: number; 
@Input() height: number; 

public styleObject: Object = { 
    'height': this.height, 
    'width': this.width 
}; 

但出於某種原因<div [ngStyle]="styleObject"></div>沒有考慮到上面顯示的風格。

請注意,添加+ 'px'並做height.px不能解決我的問題。

我沒有看到什麼?

-

一些試驗已經表明

styleObject = { 
    'height': 200 + 'px', 
    'background': 'red' 
}; 

作品和被施加到div,但與this.height(類型的number)替換200沒有。

回答

2

Assalamualaikum,

當使用ngStyle應創建一個函數返回以下中的一個:串,數組或一個對象。

,如果你想返回你做一個對象如下:如果你定義styleObjectthis.height

export class AppComponent{ 
styleObject(): Object { 
     if (/** YOUR CONDITION TO SHOW THE STYLES*/ ){ 
      return {height: this.height,width: this.width} 
     } 
     return {} 
    } 
} 
+0

非常感謝! – Christopher

+0

@克里斯你不客氣克里斯!我很高興這對你有幫助:) –

0

<div [ngStyle]="styleObject()"></div> 
在組件

在模板

this.width將是未定義的。至少,在ngOnInit中定義styleObject,其中綁定將保證被初始化。

對於更加動感的感覺,用戶可以在組件渲染後更改屬性,您可以使用getters/setters。

它會是這個樣子:

export class YourComponent {  
    styleObject: {[key: string]: string} = {}; 

    @Input() 
    set width(w: string) { 
    styleObject = Object.assign({}, styleObject, {width: w}); 
    } 
    get width() { return styleObject.width; } 

    @Input() 
    set height(h: string) { 
    styleObject = Object.assign({}, styleObject, {height: h}); 
    } 
    get height() { return styleObject.height; } 
} 

你或許可以省略的干將,其實。

+0

用戶如何訪問這些設置器?編程? – Christopher

+0

設置者從模板中調用。例如: 將在寬度更改時調用寬度設置器。 – ppham27