簡體   English   中英

單擊事件更改按鈕文本和樣式上的Angular 4

[英]Angular 4 on click event change button text and style

我有一個組件與以下方法

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>

問題是現在行為是全局的,點擊會影響所有產品,但我希望點擊對個別產品是私有的。 我怎樣才能做到這一點?

您可以簡單地使用$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:基於font-awesome圖標的評論

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";
}
}

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

現場演示

我通過向模型類添加一個布爾變量來解決它。

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>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM