使用对象的角度默认值下拉列表

时间:2020-11-04 08:21:05

标签: arrays angular string object dropdown

我正在为项目使用Angular Material(最新的稳定版本),但无法使用对象在下拉菜单中设置默认值。我的代码:

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文件:

<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文件:

<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>

这是一小段代码,但是对于较大的列表/对象,这可能很困难。有人可以解释创建带字符串填充数组和带对象填充数组的下拉列表的区别以及为什么无法在对象下拉列表中设置默认值吗?

2 个答案:

答案 0 :(得分:0)

您尝试使用[[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>

答案 1 :(得分:0)

您进行了一些输入错误(并在模板中重复使用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>

(请注意selectedObjectselectableObject[value]绑定和compareObjects函数之间的区别)

TypeScript

public compareObjects = function (option, value): boolean {
    return option.key === value.key;
}