如何从$ event获取有角项目?

时间:2019-04-19 19:43:23

标签: angular angular7

我在页面上显示一组对象数组。每个对象都有一个click事件。我想用包装器一键式替换很多单击事件(现在已经超过三千个单击事件)。 例如,当前代码

<div *ngFor="var service of services">
  <div *ngFor="var cat of service.cats">
    <div (click)="catClick(cat)">{{cat.name}}</div>
    <div (click)="increaseQuantity(cat)">+</div>
    <div (click)="decreaseQuantity(cat)">-</div>
  </div>
</div>

所需代码

<div (click)="someCommonFunc($event)">
  <div *ngFor="var service of services">
    <div *ngFor="var cat of service.cats">
      <div>{{cat.name}}</div>
      <div>+</div>
      <div>-</div>
    </div>
  </div>
</div>

但是在event.target中,我仅获得元素的HTML代码。 如何获得已绑定到该html-element的棱角对象?

2 个答案:

答案 0 :(得分:1)

您可以在元素上放置一些HTML属性。在模板中

<div (click)="onClick($event)">
  <button *ngFor="let btn of buttons; let i = index"
     [attr.data-name]="btn" [attr.data-index]="i">
     {{btn}}
  </button>
</div>

和TS

  onClick(event) {
    console.log(event.target.dataset.name, event.target.dataset.index);
  }

https://stackblitz.com/edit/angular-plfldc

答案 1 :(得分:1)

要获得预期的结果,请使用以下使用类名和事件的选项

  1. 将$ event和cat对象传递给第二个循环点击事件
  2. 使用event.target.className,更新cat对象

.text {
    position:absolute;
    left: 500px;
    font-size:28px;
    transform: translateX(-50%);
}
import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "CodeSandbox";
  displayCat = "";
  services = [
    {
      cats: [{ name: "1aaa1", quantity: 10 }, { name: "1aaa2", quantity: 10 }]
    },
    {
      cats: [{ name: "2aaa1", quantity: 20 }, { name: "2aaa2", quantity: 20 }]
    }
  ];
  

  test(event, cat) {
    if (event.target.className === "increase") {
      cat.quantity++;
    }

    if (event.target.className === "decrease") {
      cat.quantity--;
    }

    if (event.target.className === "cat") {
      this.displayCat = cat.name;
    }
  }
}

codesandbox-https://codesandbox.io/s/20zzjqzm3n