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

相关内容

热门资讯

我来教教你!微乐小程序游戏破解... 我来教教你!微乐小程序游戏破解器,微乐小程序免费脚本-竟然有辅助app(揭秘有挂)1、起透看视 微乐...
科技揭秘!微乐小程序游戏破解器... 您好,微乐小程序游戏破解器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
免费测试版!微信微乐小程序修改... 免费测试版!微信微乐小程序修改器,手机微乐小程序破解器如何使用-原来真的有辅助工具(有挂方式)1、完...
必知教程!微乐小程序免费工具,... 必知教程!微乐小程序免费工具,微乐江苏自建房辅助app-都是存在有辅助挂(有挂秘诀)1、微乐小程序免...
推荐十款!微乐小程序脚本工具平... 推荐十款!微乐小程序脚本工具平台,微信小程序微乐辅助-果然是真的有辅助app(有挂讲解)1、玩家可以...
今日科普!微信小程序微乐辅助器... 今日科普!微信小程序微乐辅助器,微乐广西麻辣辅助器-原来是有辅助教程(有挂方法)1、游戏颠覆性的策略...
玩家必看科普!微乐小程序家乡自... 玩家必看科普!微乐小程序家乡自建房辅助app,微乐自建房辅助可信吗-确实是有辅助技巧(有挂透视)一、...
一分钟揭秘!微信微乐小程序有挂... 一分钟揭秘!微信微乐小程序有挂黑科技,微乐家乡官方免费下载安装-真是真的有辅助攻略(有挂分析)1、微...
普及知识!微信微乐小程序辅助器... 普及知识!微信微乐小程序辅助器免费安装,微信微乐陕西小程序破解器-都是有辅助插件(新版有挂)1)微信...
教程攻略!微乐小程序辅助工具,... 教程攻略!微乐小程序辅助工具,收i就微乐小程序游戏破解器-切实是真的有辅助插件(有挂分析)一、微乐小...