如何将初始值设置为“角材料”,请选择将对象列表用作选项的倍数。可以在stackblitz
上找到并运行该代码这是HTML:
<form [formGroup]="formGroup">
<mat-form-field>
<mat-label>Toppings</mat-label>
<mat-select formControlName="toppings" multiple>
<mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping.name}}</mat-option>
</mat-select>
</mat-form-field>
</form>
这是打字稿:
@Component({
selector: 'select-multiple-example',
templateUrl: 'select-multiple-example.html',
styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample implements OnInit {
constructor(private formBuilder: FormBuilder) { }
formGroup = this.formBuilder.group({ 'toppings': [null, Validators.required] });
toppingList: any[] = [
{ id: 1, name: 'Extra cheese' },
{ id: 2, name: 'Mushroom' },
{ id: 3, name: 'Onion' }
];
ngOnInit() {
this.formGroup.controls.toppings.setValue([{ id: 1 }]);
}
}
答案 0 :(得分:3)
看来您必须传递整个对象。
替换
this.formGroup.controls.toppings.setValue([{ id: 1 }]);
使用
this.formGroup.controls.toppings.setValue([this.toppingList[0]]);
答案 1 :(得分:1)
如果尝试绑定整个对象角度,则将通过比较它们的参考来检查是否选择了对象。我建议您绑定对象的ID,因为它是唯一的:
this.formGroup.controls.toppings.setValue([1]);
和HTML
<mat-option *ngFor="let topping of toppingList" [value]="topping.id">{{topping.name}}</mat-option>
使您的堆叠闪电战工作
答案 2 :(得分:0)
这是工作示例
.html
<form [formGroup]="formGroup">
<mat-form-field>
<mat-label>Toppings</mat-label>
<mat-select formControlName="toppings" multiple (selectionChange)=" showSelectValue($event.value)">
<mat-option *ngFor="let topping of toppingList" [value]="topping.name"
>{{topping.name}}</mat-option>
</mat-select>
</mat-form-field>
<p>You selected: {{selected}}</p>
</form>
.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
/** @title Select with multiple selection */
@Component({
selector: 'select-multiple-example',
templateUrl: 'select-multiple-example.html',
styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample implements OnInit {
selected: any[];
constructor(private formBuilder: FormBuilder) { }
formGroup = this.formBuilder.group({ 'toppings': [null, Validators.required] });
toppingList: any[] = [
{ id: 1, name: 'Extra cheese' },
{ id: 2, name: 'Mushroom' },
{ id: 3, name: 'Onion' },
{ id: 4, name: 'Pepperoni' },
{ id: 5, name: 'Sausage' },
{ id: 6, name: 'Tomato' }
];
ngOnInit() {
this.formGroup.controls.toppings.setValue(this.selected);
}
showSelectValue(mySelect)
{
this.selected=mySelect;
console.log(mySelect);
}
}
/** Copyright 2019 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license */
答案 3 :(得分:0)
您可以在this.formBuilder.group(例如列表的第二和第四项)中设置初始值
formGroup = this.formBuilder.group({ 'toppings': [[1, 3], Validators.required] });
和html
<mat-option *ngFor="let topping of toppingList" [value]="topping.id">{{topping.name}}</mat-option> makes your stackblitz work