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

Angular TypeScript如何根据id禁用指定按钮并在其他组件展示点击卡片信息

Angular 功能实现方案

1. 实现点击Like按钮仅禁用当前被点击按钮

原有全局isDisabled变量会导致所有按钮同时禁用,我们需要给每个卡片单独标记点赞状态,同时存储已点赞的卡片数据供后续表格组件使用:

修改TS代码

// 实体类新增点赞状态字段
export class uneListe {
  id: number = 0;
  txt: string = '' ;
  image: string = '';
  titre: string = '';
  // 新增:标记当前卡片是否被点赞
  isLiked: boolean = false;
}

export class AppComponent {
  public list: Array<uneListe> = [];
  // 新增:存储所有已点赞的卡片数据,用于传给表格组件
  public likedItems: Array<uneListe> = [];
  title = 'Projettodo';

  constructor(){
    let l: uneListe = { id: 1, titre : '1 Ultra - PINK', isLiked: false}
    this.list.push(l);
    l = { id: 2, titre : '2 Ultra - PINK', isLiked: false}
    this.list.push(l);
    l = { id: 3, titre : '3 Ultra - PINK', isLiked: false}
    this.list.push(l);
  }

  didLike(n: uneListe) {
    if (!n) return;
    console.log(n.id);
    // 标记当前卡片为已点赞,对应按钮会自动禁用
    n.isLiked = true;
    // 把已点赞卡片加入集合,避免重复添加
    if(!this.likedItems.find(item => item.id === n.id)){
      this.likedItems.push(n);
    }
  }

  didsave(n: uneListe){
    // 保留你原有save逻辑即可
  }
}

修改模板HTML代码

把按钮的禁用条件改成当前卡片自身的点赞状态:

<mat-grid-list cols="3" rowHeight="1:2" >
  <div *ngFor="let element of list">
  <mat-grid-tile>
    <mat-card>
      <img src="{{element.image}}">
        <h2>{{element.titre}}</h2>
        <p>{{element.txt}}</p>
        <!-- 禁用条件改成当前卡片的isLiked属性,仅当前被点击按钮禁用 -->
        <button  (click) ="didLike(element)" [disabled]="element.isLiked">LIKE</button>
        <button   (click) ="didsave(element)" >SAVE</button>
    </mat-card>
  </mat-grid-tile>
</div>
</mat-grid-list>

<!-- 引入表格组件,传入已点赞的卡片数据 -->
<app-liked-table [likedList]="likedItems"></app-liked-table>

2. 实现独立表格组件展示已点赞卡片信息

先创建独立的liked-table组件,代码如下:

表格组件TS代码(liked-table.component.ts)

import { Component, Input } from '@angular/core';
import { uneListe } from '../app.component'; // 路径根据你的实际项目结构调整

@Component({
  selector: 'app-liked-table',
  templateUrl: './liked-table.component.html',
  styleUrls: ['./liked-table.component.css']
})
export class LikedTableComponent {
  // 接收父组件传过来的已点赞卡片列表
  @Input() likedList: Array<uneListe> = [];
}

表格组件模板代码(liked-table.component.html)

<h3>已点赞卡片列表</h3>
<table border="1" cellpadding="8" cellspacing="0" *ngIf="likedList.length>0;else emptyTip">
  <thead>
    <tr>
      <th>卡片ID</th>
      <th>标题</th>
      <th>描述</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of likedList">
      <td>{{item.id}}</td>
      <td>{{item.titre}}</td>
      <td>{{item.txt || '无描述'}}</td>
    </tr>
  </tbody>
</table>
<ng-template #emptyTip>
  <p>暂无点赞的卡片</p>
</ng-template>

如果使用Angular Material的mat-table,替换对应表格代码即可,数据传递逻辑完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:51:01