gpt4 book ai didi

mongodb - Angular 5/Material 2 - 选择选项后字段中的值错误

转载 作者:IT老高 更新时间:2023-10-28 13:16:05 26 4
gpt4 key购买 nike

我的 Angular Material 2 Autocomplete 遇到问题字段。

这是我的设置:

hardwareCreate.component.ts

myControl: FormControl = new FormControl();
availableFirmware = [];
filteredFirmware: Observable<any[]>;
selectedFirmware = null;
selectedFirmwareName = '';



this.availableFirmware = [];

this.terminalService.getFirmware().subscribe(firmware => {
this.availableFirmware = firmware.firmware;
});
this.filteredFirmware = this.myControl.valueChanges
.pipe(
startWith(''),
map(val => this.filterFirmware(val))
);

filterFirmware(val: any): any[] {
return this.availableFirmware.filter(firmware => {
return firmware.name.toLowerCase().indexOf(val.toLowerCase()) > -1;
});
}

hardwareCreate.component.html

<div class="form-group">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Firmware auswählen" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto1" [(ngModel)]="selectedFirmwareName">
<mat-autocomplete #auto1="matAutocomplete">
<mat-option *ngFor="let firmware of filteredFirmware | async" [value]="firmware._id">
{{ firmware.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>

所以我现在的问题是,当我键入时,我得到了正确的firmware.name 属性,如下所示: enter image description here

但是当我现在选择固件时,value 变为 firmware_identer image description here

所以我可以将 [value]="firmware._id" 更改为 [value]="firmware.name" 但我需要我的 mongodb 的 ID ->

firmware: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Firmware'
},

问题:当用户选择特定固件时,如何将显示值更改为名称,但仍获取我的数据库的 ID?


现在的解决方案是结合 vsoni 和 JEY 的答案。最后的问题是,val 是一个对象。通过将其转换为字符串,任何东西都可以像魅力一样工作!谢谢你们!

最佳答案

您可以使用 displayWith 功能。

你的 component.html 会变成

<div class="form-group">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Firmware auswählen" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto1">
<mat-autocomplete #auto1="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let firmware of filteredFirmware | async" [value]="firmware" (onSelectionChange)="getXXX(firmware)>
{{ firmware.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>

然后在你component.ts

中定义如下显示函数
displayFn(firmware: any): string {
return firmware? firmware.name : firmware;
}

您可以在 component.ts 中定义的 getXXX(firmware) 函数中访问固件 ID。此函数将在选择更改时调用。

getXXX(firmware) {
this.selectedFirmware = firmware;
// here you can get id
// firmware._id
}

及过滤功能

filterFirmware(val: any): any[] {
let name = val.name ? val.name : val;
return this.availableFirmware.filter(firmware => {
return firmware.name.toLowerCase().indexOf(name.toLowerCase()) > -1;
});
}

关于mongodb - Angular 5/Material 2 - 选择选项后字段中的值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48340283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com