2017-08-26 61 views
0

角4我有以下方法上單擊事件改變按鈕文字,樣式

onProductAdded(product: ImportList) { // Add an Item to ImportList 
    // after some logic add product to ImportList 
    this.productIsOnImportList = true; 
    console.log('product added'); 
    } 

    onProductRemoved(product: ImportList) { 
    this.productIsOnImportList = false; 
    console.log('product removed'); 
    } 

而在HTML模板我有

<button 
(click)="onProductAdded(product)" 
*ngIf="!productIsOnImportList" 
class="ui labeled icon blue button"> 
<i class="plus icon"></i> 
    Add to Import List 
</button> 
<button 
(click)="onProductRemoved(product)" 
*ngIf="productIsOnImportList" 
class="ui labeled icon red button"> 
<i class="minus icon"></i> 
    Remove 
</button> 

的問題是,現在的行爲是一個組件全球,點擊影響所有產品,但我希望點擊對個人產品是私人的。我怎樣才能做到這一點?

回答

1

您可以簡單地使用$event實現這個,而不是有兩個單獨的按鈕

onProductAdded(event){ 
    if(event.srcElement.innerHTML ==='Add to Import List'){ 
     //// perform add action 
     event.srcElement.innerHTML="Remove"; 
    } else if(event.srcElement.innerHTML ==='Remove'){ 
     //// perform remove action 
     event.srcElement.innerHTML="Add to Import List"; 
    } 

    } 

HTML

<button (click)="onProductAdded($event)">Add to Import List</button> 

更新1:基於對字體真棒圖標

onProductAdded(event){ 
if(event.srcElement.childNodes[1].textContent === 'Add to Import List'){ 
    //// perform add action 
    event.srcElement.childNodes[0].classList.remove('fa-plus'); 
    event.srcElement.childNodes[0].classList.add('fa-times'); 
    event.srcElement.childNodes[1].textContent="Remove"; 
} else if(event.srcElement.innerText ==='Remove'){ 
    //// perform remove action 
    event.srcElement.childNodes[0].classList.add('fa-plus'); 
    event.srcElement.childNodes[0].classList.remove('fa-times'); 
    event.srcElement.childNodes[1].textContent="Add to Import List"; 
} 
} 
評論

注意:現場演示也會更新。

LIVE DEMO

+0

感謝您的回答,首先要做到這一點的原因並不完全可以實現。產品對象不通過。其次,正如你可以看到按鈕的CSS類和圖標在每種情況下都是不同的。所以這個答案不會完全工作,因爲我不僅試圖改變產品上添加的文本,即時通訊試圖改變整個按鈕。 – mayorsanmayor

+0

@mayorsanmayor掛在一分鐘我工作只 – Aravind

+0

@mayorsanmayor看看我更新的答案。 – Aravind

0

我加入一個布爾變量來我的模型類解決它。

export interface ImportList { 
    id: number; 
    added?: boolean; 
} 

然後在這個類中,我改變了方法

onProductAdded(product: ImportList) { // Add an Item to ImportList 
    // after some logic add product to ImportList 

    //this.importList.push(product); 
    product.added = true; 
    console.log('product added'); 
    } 

onProductRemoved(product: ImportList) { 
    product.added = false; 
    console.log('product removed'); 
    } 

而且在模板我這樣做。

<button 
(click)="onProductAdded(product)" 
*ngIf="!product.added" 
class="ui labeled icon blue button"> 
<i class="plus icon"></i> 
    Add to Import List 
</button> 
<button 
(click)="onProductRemoved(product)" 
*ngIf="product.added" 
class="ui labeled icon red button"> 
<i class="minus icon"></i> 
    Remove 
</button> 

通過這樣做,我能夠聽取點擊各個產品。我希望這可以幫助別人。