Angular2: how bind to select multiple

后端 未结 6 424
陌清茗
陌清茗 2020-11-30 08:35

I\'m able to bind using ngModel for a single select but I would like to bind an array to the multiple selected options. When I attempt this I get the error

6条回答
  •  悲哀的现实
    2020-11-30 09:18

    As others have said, it's not supported by default in Angular2 yet. I thought to post this, it seems rather much simpler workaround. Here is a sample HTML:

    
    

    And myClass with a setSelected function:

    ...
    export class myClass { 
        ...
        myOptions: [];
        ...
        setSelected(selectElement) {
            for (var i = 0; i < selectElement.options.length; i++) {
                var optionElement = selectElement.options[i];
                var optionModel = this.myOptions[i];
    
                if (optionElement.selected == true) { optionModel.selected = true; }
                else { optionModel.selected = false; }
            }
        }
    }
    ...
    

    Any time you need a reference to selected items, you can use:

    var selectedItems = this.myOptions.filter((item) => { return item.selected === true; });
    

提交回复
热议问题