我在页面上显示了一组对象数组。每个对象都有一个点击事件。我想通过一次点击包装来替换那么多点击事件(现在它超过三千个点击事件)。例如,当前代码
<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元素上的角度对象?
要获得预期结果,请使用以下使用类名和事件的选项
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
您可以在元素上放置一些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);
}