Angular下拉列表多选不带复选框无法正常工作
创始人
2024-10-30 03:00:58
0次

为了使不带复选框的多选下拉列表正常工作,我们需要通过使用ngModel和ngModelChange来实现选择的跟踪和更新。以下是一个示例代码:

HTML模板:


    
        
            {{fruit.viewValue}}
        
    

组件:

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  fruits = [
    { value: 'apple', viewValue: 'Apple' },
    { value: 'orange', viewValue: 'Orange' },
    { value: 'banana', viewValue: 'Banana' },
    { value: 'grape', viewValue: 'Grape' }
  ];
  fruitSelect = new FormControl('');

  ngOnInit() {
    this.fruitSelect.valueChanges.subscribe(() => {
      const selectedFruits = this.fruits.filter(
        fruit => this.getFruitSelection(fruit.value)
      );
      console.log('Selected fruits:', selectedFruits);
    });
  }

  getFruitSelection(fruitValue: string) {
    return this.fruitSelect.value && this.fruitSelect.value.indexOf(fruitValue) > -1;
  }

  onDropdownOpened() {
    // Set the previous value of the select as the initial value when the dropdown is opened
    this.fruitSelect['_previousValue'] = this.fruitSelect.value;
  }

  onDropdownClosed() {
    // Revert to the previous value if empty input is submitted
    if (!this.fruitSelect.value || this.fruitSelect.value.length === 0) {
      this.fruitSelect.setValue(this.fruitSelect['_previousValue']);
    }
  }

}

在这个示例中,我们使用了mat-select

相关内容

热门资讯

实测分享!仁怀麻将透视挂脚本软... 实测分享!仁怀麻将透视挂脚本软件,仁怀麻将都是是真的有透视挂科普技巧仁怀麻将是不是有人用挂微扑克wp...
盘点一款!闲来老版本辅助器脚本... 盘点一款!闲来老版本辅助器脚本软件,闲来老版本原来是真的有辅助器推荐脚本闲来老版本能透视中分为三种模...
每日必备!天天卡五星2透视脚本... 每日必备!天天卡五星2透视脚本软件,天天卡五星2切实真的有透视分享技巧1.天天卡五星2 选牌创建新账...
记者爆料!非常竞技透视挂脚本软... 记者爆料!非常竞技透视挂脚本软件,非常竞技总是是真的有透视挂辅助app非常竞技脚本下载中分为三种模型...
详细说明!蚌埠玩透视脚本软件,... 详细说明!蚌埠玩透视脚本软件,蚌埠玩都是存在有透视详情方法1、金币登录送、破产送、升级送、活动送。详...
必备教程!阳新麻将透视脚本软件... 必备教程!阳新麻将透视脚本软件,阳新麻将原来真的有透视普及脚本1、阳新麻将模拟器是什么优化,阳新麻将...
揭秘几款!微竞吉林麻将白城辅助... 揭秘几款!微竞吉林麻将白城辅助器脚本软件,微竞吉林麻将白城总是是有辅助器关于技巧小薇(辅助器软件下载...
终于知道!微乐碰胡辅助脚本软件... 终于知道!微乐碰胡辅助脚本软件,微乐碰胡果然是真的有辅助必备app1、任何微乐碰胡透视是真的假的的玩...
一分钟教你!启辰开挂脚本软件,... 您好,启辰这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏...
玩家亲测!全民游戏开挂脚本软件... 玩家亲测!全民游戏开挂脚本软件,全民游戏果然真的是有开挂了解脚本1、每一步都需要思考,不同水平的挑战...