我的项目使用的是Angular Material(最新稳定版本(,无法使用Object在下拉列表中设置默认值。我的代码:
TS-FILE:
selectedObject: any;
selectedObjectList: any = [{ key: 1, value: 'One' }, { key: 2, value: 'Two' }, { key: 3, value: 'Three' }];
changeMatObject(value: any) {
console.log('MatObject value: ', value);
}
ngOnInit(): void {
this.selectedObject = { key: 1, value: 'One'};
}
HTML-FILE:
<mat-form-field>
<mat-select [(value)]="selectedObject">
<mat-option *ngFor="let selectedObject of selectedObjectList; let i = index" value="{{selectedObject.key}}"
(click)="changeMatObject(selectedObject.value)">
{{selectedObject.value}}
</mat-option>
</mat-select>
</mat-form-field>
显然,当HTML[(value(]中的值设置为字符串时,可以设置默认值,例如:
TS-FILE:
selectedString: any;
selectedStringList: any = ['One', 'Two', 'Three'];
changeMatString(value: any) {
console.log('MatString value: ', value);
}
ngOnInit(): void {
this.selectedObject = 'One';
}
HTML-FILE:
<mat-form-field>
<mat-select [(value)]="selectedString">
<mat-option *ngFor="let selectedString of selectedStringList; let i = index" value="{{selectedString}}"
(click)="changeMatString(selectedString)">
{{selectedString}}
</mat-option>
</mat-select>
</mat-form-field>
这是一小段代码,但对于较大的列表/对象,这可能会很困难。有人能解释一下创建一个用字符串填充的数组和一个用对象填充的数组的下拉列表的区别吗?为什么不能在对象下拉列表中设置默认值?
您是否尝试使用[(ngModel(]代替[(value(]?
<mat-form-field>
<mat-select [(ngModel)]="selectedString">
<mat-option *ngFor="let string of selectedStringList; let i = index" value="{{string}}"
(click)="changeMatString(string)">
{{string}}
</mat-option>
</mat-select>
</mat-form-field>
您犯了一些拼写错误(并在模板中重新使用了selectedObject
(,您需要一种比较对象的方法:
HTML
<mat-form-field>
<mat-select [(value)]="selectedObject" [compareWith]="compareObjects">
<mat-option *ngFor="let selectableObject of selectedObjectList; let i = index" [value]="selectableObject"
(click)="changeMatObject(selectableObject.value)">
{{selectableObject.value}}
</mat-option>
</mat-select>
</mat-form-field>
(注意selectedObject
和selectableObject
之间的差异,[value]
结合和compareObjects
功能(
TypeScript
public compareObjects = function (option, value): boolean {
return option.key === value.key;
}