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

相关内容

热门资讯

玩家必看教程!hhpoker必... 玩家必看教程!hhpoker必备开挂(辅助挂)竟然有挂(有挂方法)1、下载好hhpoker必备开挂透...
一分钟揭秘!we-poker有... 一分钟揭秘!we-poker有人玩吗(辅助挂)竟然真的是有挂(证实有挂)该软件可以轻松地帮助玩家将w...
发现玩家!poker worl... 发现玩家!poker world辅助(辅助挂)本来真的是有挂(有挂神器)1、实时poker worl...
揭秘关于!哈糖大菠萝开挂(辅助... 揭秘关于!哈糖大菠萝开挂(辅助挂)总是是真的有挂(有挂方法)1、首先打开哈糖大菠萝开挂辅助器下载最新...
必看攻略!德普之星透视辅助软件... 必看攻略!德普之星透视辅助软件下载(辅助挂)都是存在有挂(真的有挂)运德普之星透视辅助软件下载辅助工...
玩家必知教程!wepoker怎... 玩家必知教程!wepoker怎么看牌型(辅助挂)其实有挂(有挂教程)1、金币登录送、破产送、升级送、...
我来分享!约局吧能不能开挂(辅... 我来分享!约局吧能不能开挂(辅助挂)总是真的是有挂(有挂透视)亲,关键说明,约局吧能不能开挂透视脚本...
技术分享!wepoker免费脚... 技术分享!wepoker免费脚本咨询(辅助挂)竟然真的是有挂(有挂攻略)一、wepoker免费脚本咨...
重大通报!wepoker免费钻... 重大通报!wepoker免费钻石(辅助挂)切实有挂(真的有挂)1、全新机制【wepoker免费钻石a...
实测揭晓!wepoker怎么设... 实测揭晓!wepoker怎么设置房间(辅助挂)本来有挂(有挂规律)1、点击下载安装,wepoker怎...