【发布时间】:2017-07-02 19:34:57
【问题描述】:
我在获取 Angular2 应用程序上的选择框以在页面加载时显示默认选项“--please select--”时遇到问题。我之前已经设法让它工作,但我似乎无法在这个特定的情况下让它工作。我将展示我的代码,然后在展示时进行解释。
这是我的相关控制器代码:
import {Component} from "@angular/core";
import {ProductService} from "../../services/product.service";
import {Subscription} from "rxjs";
import {ActivatedRoute} from "@angular/router";
@Component({
selector : 'product',
moduleId : module.id,
templateUrl : '/app/views/products/product-view.html'
})
export class ProductComponent {
private id:number;
private _subscription: Subscription;
public product;
private price;
private quantity = 0;
constructor(
private _productService: ProductService,
private _activatedRoute: ActivatedRoute
) {
}
getProduct(productId: number) {
this._productService.getProduct(productId)
.subscribe((response) => {
response.success.product.options.forEach((option) => {
this[option.name] = {
name: '-- please select --',
product_option_value_id: 0,
price: 0,
price_prefix: '+'
};
option.product_option_value.unshift({
name: '-- please select --',
product_option_value_id: 0,
price: 0,
price_prefix: '+'
});
});
this.product = response.success.product;
this.generatePrice();
});
}
changeOption(optionValueId, option) {
if(optionValueId != 0) {
let selectedOptionValue = option.product_option_value.filter((option) => {
return option.product_option_value_id == optionValueId;
});
this[option.name] = selectedOptionValue[0];
} else {
this[option.name] = {
name: '-- please select --',
product_option_value_id: 0,
price: 0,
price_prefix: '+'
};
}
this.generatePrice();
}
.....
在这里,我正在获取有关以数组形式包含“选项”的产品的信息。这个对象数组被迭代以在稍后出现的视图代码中创建选择框。我为每个选项添加了一个默认的'-- please select --' 对象,并使用 unshift 将其放在数组的前面。然后,我还在该行中为此设置了控制器值:
this[option.name] = {
name: '-- please select --',
product_option_value_id: 0,
price: 0,
rice_prefix: '+'
};
相关视图代码如下:
<div class='product-options'>
<div class='option' *ngFor='let option of product.options; let i = index'>
<p class='option-name' [innerHTML]='option.name'></p>
<select name='option.name' [ngModel]='option.name' (ngModelChange)='changeOption($event, option)' required>
<option *ngFor='let productOptionValue of option.product_option_value; let j = index;' [value]='productOptionValue.product_option_value_id'>{{ productOptionValue.name }}</option>
</select>
</div>
<div class='price' ngDefaultControl [(ngModel)]="price">{{ price | currency:'GBP':true:'1.2-2' }}</div>
<div class='add-to-basket-wrap'>
<button class='add-to-basket'>add to basket</button>
<button class='increment' (click)="changeQuantity('down')">-</button>
<input type='text' name='quantity-to-add' [(ngModel)]="quantity" (click)='addToBasket()' />
<button class='increment'(click)="changeQuantity('up')">+</button>
</div>
</div>
在这里,我遍历选项,然后遍历这些选项的值以生成选择框。我将选择的 [ngModel] 属性设置为与保存在我的控制器中的属性相同。我的印象是 Angular2 会检测到此绑定,发现该值与控制器值相同,然后自动将其设置为“选定”默认选项。
谁能明白为什么这不起作用?
谢谢
【问题讨论】:
标签: forms angular drop-down-menu