【问题标题】:Angular2: how bind to select multipleAngular2:如何绑定选择多个
【发布时间】:2016-05-12 02:01:09
【问题描述】:

我可以使用ngModel 绑定单个选择,但我想将一个数组绑定到多个选择的选项。当我尝试这个时,我得到了错误

在“myModelProperty”中找不到不同的支持对象“xxx”

我的代码

<select multiple [(ngModel)]="myModelProperty">
    <option *ngFor="#item of myOptions" [value]="item.value">{{item.name}}</option>
</select>

【问题讨论】:

标签: angular


【解决方案1】:

使用ng-select

<ng-select [multiple]="true" [items]="items" (selected)="selected($event)"
                        (removed)="removed($event)" placeholder="Select the technologies" required>
</ng-select>

这里的项目是一个数组,当您取消选择选定的element.selected 元素时,您希望显示为list.remove 事件触发,当您从数组项中选择某些内容时触发

【讨论】:

    【解决方案2】:

    为什么所有这些关于简单问题的复杂答案。

    如果您事先有必须选择的选项,您可以这样做:

    这段代码不错

    HTML

    <select multiple [(ngModel)]="myModelProperty">
        <option *ngFor="#item of myOptions" [value]="item.value">{{item.name}}</option>
    </select>
    

    角度

    myModelProperty: any;
    myModelProperty = ['YOUR_VALUE', 'YOUR_VALUE'];
    

    或者如果你有字符串,你可以解析它

    myModelProperty: any;
    myModelProperty = string.split(',');
    

    所以,您所要做的就是选择标签中的 [(ngModel)] 必须在角度部分用一些对应于 [value] 来自选项标签

    这将根据数组中的值自动选择一个或多个选项。

    【讨论】:

    • 不幸的是,这种方法不会在页面加载时将所选选项标记为此类。 IE。 selected 属性未在与 myModelProperty 中的条目对应的选项上设置。
    • 使用 for 的选定属性和索引来放置将评估为 true 的条件
    【解决方案3】:

    正如其他人所说,Angular2 默认不支持它。我想发布这个,它似乎更简单的解决方法。这是一个示例 HTML:

    <select multiple (change)="setSelected($event.target)">
        <option *ngFor="#item of myOptions" [value]="item.value">{{item.name}}</option>
    </select>
    

    myClass 带有setSelected 函数:

    ...
    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; }
            }
        }
    }
    ...
    

    任何时候你需要参考选定的项目,你可以使用:

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

    【讨论】:

      【解决方案4】:

      这是一个支持双向数据绑定的多选列表实现。我使用@ViewChild 而不是getElementById()

      @Component({
        selector: 'my-app',
        template: `{{title}}<p>
        <select #select multiple (change)="change($event.target.options)">
          <option *ngFor="#item of myOptions" [value]="item.value">
            {{item.name}}
          </option>
        </select>
        <br><button (click)="changeOptions()">select 1 and 3</button>
        <p>{{selectedValues | json}}`
      })
      export class AppComponent {
        @ViewChild('select') selectElRef;
        title = "Angular 2 beta - multi select list";
        myOptions = [ 
          {value: 1, name: "one"}, 
          {value: 2, name: "two"},
          {value: 3, name: "three"}];
        selectedValues = ['1','2'];
        myModelProperty = this.myOptions[0];
        constructor() { console.clear(); }
        ngAfterViewInit() {
          this.updateSelectList();
        }
        updateSelectList() {
          let options = this.selectElRef.nativeElement.options;
          for(let i=0; i < options.length; i++) {
            options[i].selected = this.selectedValues.indexOf(options[i].value) > -1;
          }
        }
        change(options) {
          this.selectedValues = Array.apply(null,options)  // convert to real Array
            .filter(option => option.selected)
            .map(option => option.value)
        }
        changeOptions() {
          this.selectedValues = ['1','3'];
          this.updateSelectList();
        }
      }
      

      Plunker

      每当selectedValues属性被某些组件逻辑改变时,updateSelectList()也必须被调用,如“选择1和3”按钮回调逻辑所示。

      为了更容易重用,这可能应该被重构为一个属性指令。 (有接受者吗?)

      【讨论】:

        【解决方案5】:

        在angular2中使用纯javascript选择/选择多个选项的另一种方法。这是我们必须在 .html 文件中编写的代码:

           <div class="multiselect">
              <div class="selectBox(click)="showCheckboxes('checkboxes1',batchEvent); batchEvent=!batchEvent">
                <select class="form-control">
                  <option selected disabled>Select Batch</option>
                </select>
                <div class="overSelect"></div>
              </div>
              <div id="checkboxes1" style="display: none;">
                 <div *ngFor="#batch of batch_array">
                    <input type="checkbox" [value]="batch.id" id="E{{batch.id}}" (click)="batchSelectedEevent('E'+batch.id,batch.id)" /> {{batch.batch_name}}
                 </div>
              </div>
          </div>
        

        css 在这里:-

        .multiselect {
                width: 200px;
            }
            .selectBox {
                position: relative;
            }
            .selectBox select {
                width: 100%;
                font-weight: bold;
            }
            .overSelect {
                position: absolute;
                left: 0; right: 0; top: 0; bottom: 0;
            }
        

        在 .ts 文件或我们必须写的构造函数中:

        batchEvent:boolean= false;
        
        // Function for Multiple Select options checkbox area //
        
            showCheckboxes(ids, flag) {
                let checkboxes = document.getElementById(ids);
                if (!flag) {
                    checkboxes.style.display = "block";
                } else {
                    checkboxes.style.display = "none";
                }
            }
        
        batchSelectedholiday(id, value) {
                // console.log(id, value);
                if ((<HTMLInputElement>document.getElementById(id)).checked == true) {
                    this.batchHoliday_array.push(value);
                }
                else if ((<HTMLInputElement>document.getElementById(id)).checked == false) {
                    let indexx = this.batchHoliday_array.indexOf(value);
                    this.batchHoliday_array.splice(indexx, 1);
                }
                console.log(this.batchHoliday_array, "batchHoliday_array");
            }
        

        【讨论】:

          【解决方案6】:

          你可以在我的 plnkr 中实现你自己的。 已更新,因为 CHOW 想要没有 jquery 的示例。

          http://plnkr.co/edit/Pf92XATg3PT5RtBvrsaA?p=preview

          //our root app component
          import {Component} from 'angular2/core'
          
          @Component({
            selector: 'my-app',
            providers: [],
            styles:['.options{cursor:pointer;padding:10px;border-bottom:1px solid black;}', '.multiple-select{overflow-y:scroll; height:100px;}'],
            template: `
                <h3>{{selected|json}}</h3>
                <div class="multiple-select col-lg-6 col-md-6 col-sm-6 col-xs-6" style="">
                  <div class="options col-lg-12 col-md-12 col-xs-12 col-sm-12" *ngFor="#athlete of athletes" id={{athlete.id}} (click)="toggleMultiSelect($event, athlete)">{{athlete.name}}</div>
                </div>
            `,
            directives: []
          })
          export class App {
            public athletes:any[]=[];
            public selected:any[]=[];
            constructor() {
              for(var i = 1; i <= 5; i++){
                this.athletes.push({
                  value:i,
                  name:("athlete-"+i),
                  id:("id-"+i)
                })
              }
            } 
            toggleMultiSelect(event, val){
              event.preventDefault();
              if(this.selected.indexOf(val) == -1){
                this.selected = [...this.selected, val];
                var elem = document.getElementById(val.id);
                elem.className += " fa fa-check";
              }else{
                var elem = document.getElementById(val.id);
                elem.className = elem.className.split(' ').splice(0, elem.className.split(' ').length - 2).join(' ');
                this.selected = this.selected.filter(function(elem){
                  return elem != val;
                })
              }
            }
          }
          

          【讨论】:

          • e.values 不是在 ubuntu Linux 上显示错误的函数。
          • 它在我的电脑上工作得很好,我也有一本 chrome book 双启动 Ubuntu。
          • 感谢您的回复,我感谢您的努力,但这种 jquery 不属于控制器/视图模型。您违反了关注点分离。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-09-12
          • 2018-11-11
          • 2017-02-06
          • 2017-02-11
          • 1970-01-01
          • 2016-06-13
          • 2017-03-02
          相关资源
          最近更新 更多