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

Angular中如何通过Input/Output绑定数组并实现点击切换选中

没问题,我帮你用Angular的@Input/@Output规范实现这个互选高亮的组件,完全遵循组件通信的最佳实践~

核心实现思路

我们会通过**@Input让子组件接收父组件传递的users和selectedUsers数组,用@Output**让子组件触发事件通知父组件更新数组(避免子组件直接修改输入属性,符合Angular单向数据流原则),点击项时切换其选中状态并同步高亮样式。


1. 父组件代码

parent.component.ts

负责维护数据源(用户列表和选中列表),并处理子组件触发的切换逻辑:

import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent {
  // 初始用户列表
  users = ['One', 'Two', 'Three'];
  // 初始选中项(默认高亮Two)
  selectedUsers: string[] = ['Two'];

  // 处理子组件传来的切换请求
  toggleUser(user: string): void {
    const selectedIndex = this.selectedUsers.indexOf(user);
    if (selectedIndex > -1) {
      // 已选中:从选中列表移除(用扩展运算符创建新数组,触发变更检测)
      this.selectedUsers = [
        ...this.selectedUsers.slice(0, selectedIndex),
        ...this.selectedUsers.slice(selectedIndex + 1)
      ];
    } else {
      // 未选中:添加到选中列表
      this.selectedUsers = [...this.selectedUsers, user];
    }
  }
}

parent.component.html

引入子组件并传递数据、绑定事件:

<app-user-selector
  [users]="users"
  [selectedUsers]="selectedUsers"
  (toggleUser)="toggleUser($event)"
></app-user-selector>

2. 子组件代码

user-selector.component.ts

接收父组件的输入数据,定义触发父组件更新的事件,提供选中状态判断方法:

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-user-selector',
  templateUrl: './user-selector.component.html',
  styles: [`
    .user-item {
      cursor: pointer;
      padding: 6px 12px;
      margin: 4px;
      border-radius: 4px;
      display: inline-block;
    }
    .selected {
      background-color: #2196F3;
      color: white;
    }
  `]
})
export class UserSelectorComponent {
  // 接收父组件的用户列表
  @Input() users: string[] = [];
  // 接收父组件的选中列表
  @Input() selectedUsers: string[] = [];
  // 定义触发父组件更新的事件
  @Output() toggleUser = new EventEmitter<string>();

  // 判断当前用户是否被选中
  isUserSelected(user: string): boolean {
    return this.selectedUsers.includes(user);
  }

  // 处理用户点击事件,通知父组件切换状态
  onUserClick(user: string): void {
    this.toggleUser.emit(user);
  }
}

user-selector.component.html

渲染用户项,动态添加高亮样式,绑定点击事件:

<div 
  *ngFor="let user of users"
  class="user-item"
  [class.selected]="isUserSelected(user)"
  (click)="onUserClick(user)"
>
  {{ user }}
</div>

关键细节说明

  • 单向数据流:子组件永远不直接修改@Input属性,而是通过@Output事件让父组件更新数据源,这是Angular的最佳实践,避免数据混乱。
  • 不可变更新:父组件中用扩展运算符创建新数组,而不是直接用push/splice修改原数组,确保Angular的变更检测能正确触发视图更新。
  • 动态样式:通过[class.selected]根据选中状态动态切换样式,实现高亮效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:23:52