加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2:如何绑定选择多个

发布时间:2020-12-17 08:09:05 所属栏目:安全 来源:网络整理
导读:我可以使用ngModel绑定一个选择,但我想绑定一个数组到多个选定的选项。当我尝试这个我得到错误 Cannot find a differ supporting object ‘xxx’ in ‘myModelProperty’ 我的代码 select multiple [(ngModel)]="myModelProperty" option *ngFor="#item of
我可以使用ngModel绑定一个选择,但我想绑定一个数组到多个选定的选项。当我尝试这个我得到错误

Cannot find a differ supporting object ‘xxx’ in ‘myModelProperty’

我的代码

<select multiple [(ngModel)]="myModelProperty">
    <option *ngFor="#item of myOptions" [value]="item.value">{{item.name}}</option>
</select>
这是一个支持双向数据绑定的多选列表实现。我使用@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”按钮回调逻辑所示。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读