2017-10-16 29 views
0

我有一個父級組件,並且在該組件中包含多次其他組件。在Angular 4中單擊相同同級組件時更改屬性

結構:

父組件:

<table> 
    <tr class=""> 
    <td>buttons</td> 
    </tr> 
    <tr app-myComp></tr> 
    <tr app-myComp></tr> 
    <tr app-myComp></tr> 
    <tr app-myComp></tr> 
</table> 

兒童(myComp)成分:

@Component({ 
selector: 'tr[app-myComp]', 
template: ` 
       <td><button [style.color]="myColor" (click)="changeColor()">changeColor</button></td>  
      ` 
}) 

export class MyComponent { 

myColor: string = "blue"; 

changeColor(): void{ 
    this.myColor = "red" 
} 
} 

當我點擊按鈕,按鈕改變文字顏色從藍色到紅色。

但我的問題是如何更改文本顏色只有點擊按鈕紅色和重置所有其他按鈕的文本顏色爲藍色?

我知道我可以通過@ViewChildren獲取MyComponent的列表,但是如何使用它們將按鈕的文本顏色重置爲藍色(除了單擊它)。

我使用的角度4.3.4

codepen鏈接:Angular 4 app

回答

1

您需要到母部件與分配的值添加屬性所點擊的子項的索引。每次單擊孩子時更改其值,並將其作爲布爾值@Input傳遞給子元素(如果屬性值等於子元素索引,則爲true,反之,則爲true)。在子組件中添加一個條件來檢查@Input並僅在該條件下設置顏色。對於子索引追蹤,請添加* ngFor而不是重複硬編碼的複數<tr app-myComp>

DEMO

子類:

... 
myColor: string; 

@Input() 
    set chosen(chosen: boolean) { 
    this.myColor = chosen ? "red" : "blue" 
    } 

... 

父視圖:

<table> 
    <tr class=""> 
    <td>buttons</td> 
    </tr> 
    <tr app-myComp (click)="chosenTr = i" [chosen]="i == chosenTr" *ngFor="let item of [1,2,3,4]; let i = index"></tr> 
</table> 

父類:

... 
    chosenTr = -1; 
    ... 
+0

謝謝! ..... – AjinkyaBhagwat

相關問題