Angular2:如何绑定选择多个

时间:2016-02-03 02:27:23

标签: angular

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

  

无法找到不同的支持对象' xxx'在myModelProperty'

我的代码

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

6 个答案:

答案 0 :(得分:18)

这是一个支持双向数据绑定的多选列表实现。我使用@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(),如“select 1 and 3”按钮回调逻辑中所示。

为了更容易重用,这可能应该重构为属性指令。 (任何人?)

答案 1 :(得分:18)

为什么所有这些都使简单问题的答案复杂化。

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

此代码良好

<强> 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] < / strong>来自选项标签

这将自动选择一个或多个选项,具体取决于数组中的值。

答案 2 :(得分:8)

正如其他人所说,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; });

答案 3 :(得分:2)

你可以在我的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;
      })
    }
  }
}

http://imgur.com/2P383hS

答案 4 :(得分:1)

使用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");
    }

答案 5 :(得分:1)

使用ng-select

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

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