单击事件更改按钮文本和样式上的Angular 4

时间:2017-08-26 18:17:55

标签: angular

我有一个包含以下方法的组件

json_1 = <your first json>
json_2 = <your second json>
for book1 in json_1['product']['books']:
    for book2 in json_2['product']['books']:
        if book1['id'] == book2['id']:
             json_1['product']['books']['price-en'] = book2['periods'][0]['price']['en']
             json_1['product']['books']['price-de'] = book2['periods'][0]['price']['de']

在html模板上我有

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');
  }

问题是现在行为是全局的,点击会影响所有产品,但我希望点击对个别产品是私有的。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

您只需使用$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";
}
}

注意:现场演示也会更新。

<强> LIVE DEMO

答案 1 :(得分: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>

通过这样做,我能够听取单个产品的点击。我希望这可以帮助别人。