You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular如何切换按钮onclick事件 实现图片增删及按钮状态切换

解决方案

1. 组件逻辑代码修改

需调整点击逻辑,补充表格删除方法,删除无用变量,完整代码如下:

data: any = [{
        "albumId": 1,
        "id": 1,
        "title": "accusamus beatae ad facilis cum similique qui sunt",
        "url": "https://via.placeholder.com/600/92c952",
        "thumbnailUrl": "https://via.placeholder.com/150/92c952"
    },
    // 剩余的data项保持原有不变,此处省略重复内容
    {
        "albumId": 1,
        "id": 15,
        "title": "harum dicta similique quis dolore earum ex qui",
        "url": "https://via.placeholder.com/600/f9cee5",
        "thumbnailUrl": "https://via.placeholder.com/150/f9cee5"
    },
];
// 存储选中项的数组保留
array: any = []

constructor() {}

ngOnInit() {

}

// 改造点击方法,支持添加/移除切换
onclick(a) {
    const existIndex = this.array.findIndex(item => item.id === a.id);
    if(existIndex > -1) {
        // 已选中,执行移除
        this.array.splice(existIndex, 1);
    } else {
        // 未选中,执行添加
        this.array.push(a);
    }
}

// 补充表格行点击删除方法
DeleteItem(id) {
    const existIndex = this.array.findIndex(item => item.id === id);
    if(existIndex > -1) {
        this.array.splice(existIndex, 1);
    }
}

2. 模板代码修改

调整按钮文本和样式的动态渲染逻辑,完整代码如下:

<div class="row">
    <div class="container col-6">
        <h1>List</h1>
        <div class="row">
            <div class="col-3" *ngFor="let a of data">
                <div class="row"><img src="{{a.url}}" style="height: 100px; padding: 10px;"> </div>
                <div class="row" style=" padding: 10px;">
                    <!-- 动态切换按钮文本、样式 -->
                    <button 
                        class="btn" 
                        [ngClass]="array.some(item => item.id === a.id) ? 'btn-danger' : 'btn-primary'"
                        (click)="onclick(a)"
                    >
                        {{ array.some(item => item.id === a.id) ? 'REMOVE' : 'Add' }}
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div class="container col-6">
        <h1>Table</h1>
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">Photo</th>
                    <th scope="col">Id</th>
                    <th scope="col">URL</th>
                    <th scope="col">Title</th>
                </tr>
            </thead>
            <tbody *ngFor="let s of array">
                <tr (click)="DeleteItem(s.id)">
                    <th scope="col"><img src="{{s.url}}" style="height: 30px; padding: 10px;"></th>
                    <th scope="col">{{s.id}}</th>
                    <th scope="col">{{s.url}}</th>
                    <th scope="col">{{s.title}}</th>
                </tr>
            </tbody>
        </table>
    </div>
</div>

内容的提问来源于stack exchange,提问作者Ganesh phadtare

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:15:04