2016-06-24 36 views
5

StackOverflow!角度2:組件中的輸入變量不會更新,一次調用

我有一些麻煩,我的代碼。正如你所看到的,我希望能夠調用一個具有設置寬度的行(引導格​​式),因爲我不想每次都輸入類。

於是我想了個辦法是以下幾點:

import { Component, Input } from '@angular/core'; 

@Component({ 
    moduleId: module.id, 
    selector: 'content', 
    template: ` <div class="row"> 
        <div [ngClass]="contentClass" 
         id="content" 
         [ngStyle]="{ 'color': 'black', 'font-size': '20px' }"> 
        <ng-content></ng-content> 
        </div> 
       </div>`, 
    styleUrls: ['content.stylesheet.css'] 
}) 

export class ContentComponent { 
    @Input() rowWidth = "12"; 
    contentClass=(("col-lg-" + this.rowWidth)+(" col-sm-" + this.rowWidth)+(" col-xs-" + this.rowWidth)); 
} 

但是,一旦我從另一個調用組件的組件,它不工作我想要的方式。

<banner bannerHeight="300px"></banner> <!-- This works --> 
<content rowWidth="6"></content>   <!-- This doesn't --> 

如果我用於例如

<content [ngStyle]="{'color': 'black'}"></content> 

操作成功。指令和導入在父組件中正確設置。

所以這裏是我的問題:我如何使它按照我想要的方式工作?

回答

4

它不工作(你所希望的方式,我假設你的意思是,你的contentClass12一個rowWidth),因爲模板實際上是初始化之前提交作業contentClass而成。

您必須實現OnInit和使用ngOnInitcontentClass與分配設置爲您rowWidth輸入:

export class ContentComponent implements OnInit{ 
    @Input() rowWidth = 12; 
    contentClass:string; 

    ngOnInit():any { 
     this.contentClass = (("col-lg-" + this.rowWidth)+(" col-sm-" + this.rowWidth)+(" col-xs-" + this.rowWidth)); 
    } 
} 

隨着<content [rowWidth]="6"></content>你的元素,然後將有col-lg-6 col-sm-6 col-xs-6代替12集作爲其CSS類。

+0

這個伎倆!我完全忘了生命週期掛鉤..菜鳥的錯誤。因此,對於contentClass來說,這樣做會是最佳實踐嗎?對每個輸入變量實施這樣的事情,還是僅僅在處理時間花在處理時間上(例如計算或連接)纔是最佳實踐? – wuhkuh

+1

那麼,如果你想在初始化時使用你的輸入,那麼是的(你最需要的時候)你需要一個生命週期鉤子。 – lexith

相關問題