2017-01-12 28 views
0

我有以下的角2部分:角2動感的風格結合

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

@Component({ 
    selector: 'generic-component', 
    templateUrl: 'generic-component.component.html', 
    styleUrls : ['generic-component.component.css'] 
}) 
export class GenericComponentComponent{  
    @Input() backCol: string = "#F0F8FF"; 
    @Input() divClass: string = "myClass"; 
    ... 
} 

與HTML模板:

<div class={{divClass}} [style.backgroundColor]="backCol"> 
    This is a div 
</div> 

模板正確呈現與默認backCol十六進制顏色可變的股利,當應用程序啓動。

但我想將backCol變量字符串更改爲另一個十六進制顏色,可能是事件。

父組件我有這樣的事情:

@Component({ 
    template: ` 
    <generic-component divClass={{myComp.divClass}} [style.backgroundCol]="myComp.backCol"> 
    </generic-component> 
    ` 
}) 
export class ParentComp{ 
    myComp = new GenericComponentComponent(); 
} 
onColorChange(){ 
    this.myComp.divClass = "mySecondClass"; 
    this.myComp.backCol = "#A22B11"; 
} 

但新的顏色並不渲染onColorChange()調用。所有其他屬性綁定(如divClass)都會更新並正確呈現。我究竟做錯了什麼?

+0

什麼是myComp應該是?那麼'this.backCol =「#A22B11」'? –

+0

它是GenericComponentComponent類的一個實例。我使用該實例將GenericComponentComponent呈現到父級的html模板中。 – ktsangop

+0

也許'this.instance.backCol =「#A22B11」'然後呢?如果不是,請提供更多關於'myComp'是什麼的信息(代碼) –

回答

1

以下是無法得到參考子組件

export class ParentComp{ 
    myComp = new GenericComponentComponent(); 
} 

您需要使用@ViewChild來獲取參考子組件的保持正確的方法: 在你的父模板:

<generic-component #child> 
</generic-component> 

此外,您不需要將類和樣式作爲輸入。既然你可以使用@ViewChild

在你父組件獲得參考孩子的屬性:

@Component({ 
    template: ` 
    <generic-component #child> 
    </generic-component> 
    ` 
}) 
export class ParentComp{ 

    @ViewChild('child') myComp; 

    onColorChange(){ 
     this.myComp.divClass = "mySecondClass"; 
     this.myComp.backCol = "#A22B11"; 
    } 
} 

編輯:更新plunkr與@ViewChildren例子。例如: https://plnkr.co/edit/a0zddtEe0Q3No4mfaKQZ?p=preview

+0

如果我有一組子組件,該怎麼辦?我想能夠在父類中創建一個GenericComponentComponent數組。 – ktsangop

+0

您可以使用@ViewChildren('child1','child2','child3')childList:QueryList; – JSNinja

+0

我想我現在明白了。我只綁定了屬性而沒有更新組件實例本身,這就是爲什麼我無法改變樣式,是正確的?謝謝! – ktsangop