如何从$ event获得角项?

问题描述 投票:2回答:2

我在页面上显示了一组对象数组。每个对象都有一个点击事件。我想通过一次点击包装来替换那么多点击事件(现在它超过三千个点击事件)。例如,当前代码

<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元素上的角度对象?

angular angular7
2个回答
1
投票

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

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

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;
    }
  }
}
<div *ngFor="let service of services">
  <div
    *ngFor="let cat of service.cats"
    class="main"
    (click)="test($event, cat)"
  >
    <div class="cat">{{cat.name}}</div>
    <div>{{cat.quantity}}</div>
    <div class="increase">+</div>
    <div class="decrease">-</div>
  </div>
</div>

Display Cat Name:
<div>{{displayCat}}</div>

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


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

© www.soinside.com 2019 - 2024. All rights reserved.