我已阅读了许多Stack Overflow问题,但似乎没有一个与我正在尝试解决的问题相关。
我有一个component.html,我的选择选项使用* ngFor从我的产品数量中获取其值
<form class="form">
<select [(ngModel)]="selectedQuantity" (ngModelChange)="setQtyValue()" name="quantitySelector">
<option *ngFor = "let totalQty of productQty; index as i" [attr.data-index] ="i" [value]="totalQty[i]">{{totalQty}}</option>
</select>
<button class="btn btn-primary" [routerLink]="['/cart']" (click)="addToCart()">
Add to bag
</button>
</form>
在我的component.ts
中selectedQuantity: Number
constructor( ) { }
setQtyValue(){
this.selectedQuantity = +this.selectedQuantity
console.log(this.selectedQuantity)
}
addToCart(){
console.log(selectedIndex)
this.productDetails.map(product =>{
console.log(this.productDetails)
this.productSelected = {
name : product.name,
pictureUrl : product.pictures,
qty : this.selectedQuantity,
timestamp : new Date().getTime()
}
})
this.cartService.addToCart(this.productSelected)
}
我已经尝试了很多方法来获取所选索引/选项的值,但它始终记录为未定义。 我需要从上面的代码更改为get以及在我的component.ts中做什么来获取其值作为数字,以便稍后我可以在我的service.ts上处理它。
答案 0 :(得分:0)
console.log(selectedIndex)
?你的意思是this.selectedQuantity
?您还没有设置selectedQuantity
的初始值,因此未定义
答案 1 :(得分:0)
您不必手动增加“选择的数量”&#39;当你使用双向数据绑定时。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<form class="form">
<select [(ngModel)]="selectedQuantity" name="quantitySelector">
<option *ngFor="let totalQty of productQty" [value]="totalQty">{{totalQty}}</option>
</select>
<button class="btn btn-primary" (click)="addToCart()">Add to bag</button>
</form>`,
})
export class AppComponent {
productQty: number[] = Array.from({ length: 99 }, (v, k) => k + 1);
selectedQuantity: Number = 1;
addToCart() {
console.log(this.selectedQuantity);
//...
}
}