#angular #find #ngfor
#angular #Найти #ngfor
Вопрос:
Я создал список устройств, где после того, как пользователь нажмет на одно из устройств, должно появиться другое поле выбора с вариантом этого устройства.
HTML:
<div class="device" *ngFor="let p of selectedDevice;">
<img class="mx-auto d-block" src="assetsrepair{{p.imgValue}}.png">
<p>{{p.text}}</p>
</div>
<select class="custom-select" (change)="variants($event.target.value)">
<option class="text-center" value="1" selected>Choose device type</option>
<option class="text-center" value="{{p.id}}" *ngFor="let p of selectedDeviceDetails;" >{{p.type}}</option>
</select>
<p *ngFor="let a of selectedDeviceDetailsVariants;"> {{a.variant}}</p>
<select class="custom-select" *ngIf="selectedDeviceDetailsVariants?.length >= 1">
<option class="text-center" value="1" selected>Choose device variant</option>
<option class="text-center" value="1" *ngFor="let a of selectedDeviceDetailsVariants;">{{a.variant}}</option>
</select>
TS:
public selectedDevice;
public selectedDeviceDetails;
public selectedDeviceDetailsVariants;
variants(value){
console.log(value);
this.selectedDeviceDetailsVariants = this.TypesVariants.filter((x)=>x.idTypes === value);
console.log(this.selectedDeviceDetailsVariants);
}
protected onInit() {
super.onInit();
this.selectedDevice = this.MyArrayType.filter((device)=>device.id === this.articleParams.ID_DevicesTypes);
this.selectedDeviceDetails = this.Types.filter((device)=>device.idMyArrayType === this.articleParams.ID_DevicesTypes);
}
MyArrayType = [
{id: 1, text: 'Device', imgValue: '1'},
{id: 2, text: 'Different device', imgValue: '2'},
];
Types = [
{id: 1, idMyArrayType: 1, type: 'Device Details' },
{id: 2, idMyArrayType: 1, type: 'Device Details' },
{id: 3, idMyArrayType: 2, type: 'Different Device Details' },
{id: 5, idMyArrayType: 2, type: 'Different Device Details' }
];
TypesVariants = [
{id: 1, idTypes: 1, variant: '1GB'},
{id: 2, idTypes: 1, variant: '2GB'},
{id: 3, idTypes: 1, variant: '3GB'},
{id: 4, idTypes: 2, variant: '4GB'},
{id: 5, idTypes: 2, variant: '5GB'},
{id: 6, idTypes: 2, variant: '6GB'},
]
Когда мы подставляем значение здесь вручную, это работает (2 в примере во второй строке):
variants(value){
console.log(value);
this.selectedDeviceDetailsVariants = this.TypesVariants.filter((x)=>x.idTypes === 2);
console.log(this.selectedDeviceDetailsVariants);
}
Но когда я использую $event.target.value — тогда это не работает, хотя консоль.в журнале указано, что он получает правильное значение.
В чем здесь проблема?
Комментарии:
1. Возможно, типы не совпадают, вы это проверяли?
2. значение представляет собой строку, а идентификатор вводит число
3. @famenev прав — я изменил idTypes на строку, и это работает прямо сейчас. Но есть ли здесь какое-либо другое решение? Я пытался преобразовать значение в число, но, похоже, это не работает
4. @Forey преобразует строку в число:
Number(value)
,parseInt(value)
илиvalue