角度6材质< mat-select>使用表单控件多次设置默认值 [英] Angular 6 Material <mat-select> multiple set default value using form control

查看:79
本文介绍了角度6材质< mat-select>使用表单控件多次设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用表单控件,这是我的html组件的代码

I am using form control here is code for my html component

<mat-form-field>
  <mat-select placeholder="Toppings" [formControl]="toppings" multiple>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping.value}}</mat-option>
  </mat-select>
</mat-form-field>

我的ts文件是

export class SelectMultipleExample {
   toppings = new FormControl();
  toppingList: any[] = [
      { id:1,value:"test 1"},
      { id:2,value:"test 2"},
      { id:3,value:"test 4"},
      { id:4,value:"test 5"},
      { id:5,value:"test 6"},
      { id:6,value:"test 7"}
    ];

  

  constructor(){
    this.bindData();
  }

  bindData(){
    const anotherList:any[]=[
      { id:1,value:"test 1"},
      { id:2,value:"test 2"}
      ]

      this.toppings.setValue(anotherList)
  }
}

我想为mat select设置默认值,如何实现这一点的任何帮助都将非常有用.我想设置多个默认值.

I want to set default value for mat select , any help how to achieve this will be great. I want to set multiple default value.

推荐答案

问题是由于您的选项是对象这一事实.为了应用选择,所选对象必须是与用于选项的对象相同的对象.修改您的代码,如下所示:

The problem is due to the fact that your options are objects. In order for the selections to be applied, the selected objects must be the same objects as the ones used for the options. Revise your code as follows:

export class SelectMultipleExample {
    toppings = new FormControl();
    toppingList: any[] = [
        { id:1,value:"test 1"},
        { id:2,value:"test 2"},
        { id:3,value:"test 4"},
        { id:4,value:"test 5"},
        { id:5,value:"test 6"},
        { id:6,value:"test 7"}
    ];

    constructor(){
        this.bindData();
    }

    bindData() {
        const anotherList: any[] = [
            this.toppingList[0],
            this.toppingList[1]
        ]

        this.toppings.setValue(anotherList)
    }
}

这篇关于角度6材质&lt; mat-select&gt;使用表单控件多次设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆