【问题标题】:Angular2 multiple Select element needs to have a few selectedAngular2 多个 Select 元素需要选择几个
【发布时间】:2017-04-08 00:10:07
【问题描述】:

用例:我有一个具有 6 种颜色的多个 Select 元素。我需要选择其中两种颜色。非常感谢。下面是我的代码,但有什么不对吗?

如果有更好的方法,请分享?

//view
<select name="wrColors" #wrColors [(ngModel)]="selectedColors" multiple >
  <option *ngFor="let color of allColors" [ngValue]="color">{{color.label}</option>
</select>

//component
allColors = [{
  id: 1,
  label: 'red',
}, {
  id: 2,
  label: 'blue',
}, {
  id: 3,
  label: 'green',
}, {
  id: 4,
  label: 'yellow',
}, {
  id: 5,
  label: 'orange',
}, {
  id: 6,
  label: 'purple',
}];

selectedColors = [{
  id: 2,
  label: 'blue',
}, {
  id: 4,
  label: 'yellow',
}];

@ViewChild('wrColors') selectColorRef: ElementRef;

ngAfterViewInit(): void {
  this.updateSelectList();
}

updateSelectList() {
    let options = this.selectColorRef.nativeElement.options;

    for (let i = 0; i < this.allColors.length; i++) {

        for (let n = 0; n < this.selectedColors.length; n++) {
            if (this.selectedColors[n].Id === this.allColors[i].Id) {

                options[i].selected = true;

            }
        }

        //options[i].selected = this.selectedColors.indexOf(options[i].value) > -1;
    }
}

【问题讨论】:

  • 您可以指定该代码面临的问题以及您尝试解决的问题。
  • 一切正常,但没有选择我的颜色。
  • 这是您要找的吗?

标签: angular


【解决方案1】:
this.preselectedIds = this.selectedArr.map(obj =>{
  return obj.id;
});
//mark
this.preselectedIds = this.selectedArr.map(function (a:any) { return a.Id; });


In option tag inside ngFor,

[attr.selected]="preselectedIds.indexOf(color.id)!=-1 ? true: false"

【讨论】:

  • 那没有选择任何东西?他们都返回false
  • preselectedArray 应该有用户选择的颜色的 id。在 ngfor 内部,我们正在检查项目的 id 是否存在于数组中,并将选项分别选择为 true 和 false
  • 我明白它在做什么,但它不起作用?请注意 [ngValue]="color" 而不是 [ngValue]="color.id" - 但这也不起作用。
  • 将 ngValue 设置为颜色是正确的,因为您希望整个对象发送到后端左右,但我不明白为什么所选选项的一切都是错误的。预选的数组是否正确?
  • 我将 this.preselected = ["1","2"] 添加到 ngOnInit()
猜你喜欢
  • 2017-02-15
  • 2012-08-08
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
相关资源
最近更新 更多