Angular mat select:以编程方式预选项目

Angular mat select:以编程方式预选项目,angular,angular-reactive-forms,angular-forms,angular-material-7,Angular,Angular Reactive Forms,Angular Forms,Angular Material 7,我试图弄清楚如何在对话框中显示一个mat select并预选一些mat选项。我创建了一个简单的示例来演示我想做什么: 在我的示例中,我希望显示一个可选择的颜色列表,并预选一些颜色。我首先通过迭代对话框TS文件中的字符串数组来创建mat select及其内容(mat选项): <mat-select placeholder="Colors" formControlName="selectedColors" multiple> <mat-option *ngFor="let

我试图弄清楚如何在对话框中显示一个mat select并预选一些mat选项。我创建了一个简单的示例来演示我想做什么:

在我的示例中,我希望显示一个可选择的颜色列表,并预选一些颜色。我首先通过迭代对话框TS文件中的字符串数组来创建mat select及其内容(mat选项):

<mat-select placeholder="Colors" formControlName="selectedColors" multiple>
   <mat-option *ngFor="let color of allColors" value="{{color}}">{{color}}</mat-option>
</mat-select>
注意第二个数组“defaultSelections”:我希望在显示对话框时预先选择这些项目。我似乎不知道该怎么做


提前感谢您的帮助

由于您使用的是
ReactiveForms
,因此可以使用
FormControl
上的默认值属性来设置
mat select
的初始值

this.defaultSelections = ['red', 'green', 'blue'];

this.form = this.formBuilder.group({
  selectedColors: [this.defaultSelections]
});

工作组。

只是,在创建表单时使用this.form=this.formBuilder.group({selectedColors:[this.defaultSelections]});。Mat select带有多个选项,期望一个包含选项值的数组。对FormControl可以存储一个数组、一个对象、一个字符串……是的,正如Eliseo所说的,您只需将单词放入[]中即可,如
selectedColors:[this.defaultSelections]
而不是
selectedColors:[]
。。工作示例我认为事情就这么简单,但显然我找错了地方。非常感谢。
this.defaultSelections = ['red', 'green', 'blue'];

this.form = this.formBuilder.group({
  selectedColors: [this.defaultSelections]
});