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

如何禁用Angular 2 Multiselect下拉框中的特定复选框(含默认选中项)

如何禁用Angular 2 Multiselect下拉框中的特定复选框选项

当然可以实现!这个angular2-multiselect组件支持通过给选项对象添加disabled属性来单独禁用某个复选框。针对你的需求,我们只需要在初始化时,给那些默认选中的项标记为禁用即可。

具体实现步骤:

  1. 初始化下拉列表和选中项数据后,遍历每个下拉选项;
  2. 检查当前选项是否在默认选中的selectedItems数组中;
  3. 对匹配的选项添加disabled: true属性,组件会自动识别并禁用对应的复选框,同时保留其选中状态。

修改后的完整TS代码:

import { Component, OnInit } from '@angular/core';
export class AppComponent implements OnInit {
  dropdownList = [];
  selectedItems = [];
  dropdownSettings = {};
  
  ngOnInit(){
    this.dropdownList = [
      {"id":1,"itemName":"India"},
      {"id":2,"itemName":"Singapore"},
      {"id":3,"itemName":"Australia"},
      {"id":4,"itemName":"Canada"},
      {"id":5,"itemName":"South Korea"},
      {"id":6,"itemName":"Germany"},
      {"id":7,"itemName":"France"},
      {"id":8,"itemName":"Russia"},
      {"id":9,"itemName":"Italy"},
      {"id":10,"itemName":"Sweden"}
    ];
    this.selectedItems = [
      {"id":2,"itemName":"Singapore"},
      {"id":3,"itemName":"Australia"},
      {"id":4,"itemName":"Canada"},
      {"id":5,"itemName":"South Korea"}
    ];

    // 给默认选中的项添加禁用标记
    this.dropdownList = this.dropdownList.map(item => {
      const isPreSelected = this.selectedItems.some(selected => selected.id === item.id);
      return {
        ...item,
        disabled: isPreSelected
      };
    });

    this.dropdownSettings = {
      singleSelection: false,
      text:"Select Countries",
      selectAllText:'Select All',
      unSelectAllText:'UnSelect All',
      enableSearchFilter: true,
      classes:"myclass custom-class"
    };
  }

  onItemSelect(item:any){
    console.log(item);
    console.log(this.selectedItems);
  }
  OnItemDeSelect(item:any){
    console.log(item);
    console.log(this.selectedItems);
  }
  onSelectAll(items: any){
    console.log(items);
  }
  onDeSelectAll(items: any){
    console.log(items);
  }
}

效果说明:

  • 标记为disabled的复选框会呈现灰色不可点击状态;
  • 默认选中的禁用项会保持选中状态,用户无法取消选择;
  • 未选中的禁用项用户也无法选中;
  • 其他正常选项不受影响,仍可自由选择/取消。

如果之后需要动态更新禁用状态,只需要重新执行上述的map逻辑,更新dropdownList即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 19:57:37