我正在做一个比萨饼订购应用程序,我有一个MenuComponent,它列出了餐厅提供的所有菜单项目。
现在这些项目被显示为带有所有信息的独立卡片。同时我还提供了一个选项来定制多个配料的项目。
现在的问题是,我显示的是该项目的基本价格,一旦用户选择了额外的配料,我想更新基本价格和额外的费用。
下面是我的menu.component.html的样子。
<div fxFlex *ngFor="let category of categories">
<h3>{{category.name}}</h3>
<div *ngFor="let item of items">
<mat-card *ngIf="item.category == category.name" class="itemcard">
<mat-card-header>
<mat-card-title>{{item.name}}</mat-card-title>
<mat-card-subtitle>{{item.category}}</mat-card-subtitle>
<span class="flex-spacer"></span>
<div>$ {{item.price_large}}</div>
</mat-card-header>
<mat-card-content>
<mat-form-field>
<mat-label>Extra Toppings</mat-label>
<mat-select multiple>
<mat-option *ngFor="let topping of toppings" [value]="topping.rate">{{topping.name}}</mat-option>
</mat-select>
</mat-form-field>
</mat-card-content>
<span class="flex-spacer"></span>
<button mat-button color="primary"><i class="fa fa-plus-circle"></i> Add to Cart</button>
</mat-card>
</div>
</div>
the 鸿沟 标签是我显示基本价格的地方,也是我想更新它的地方,当选择额外的配料时。我在某处读到过使用2路绑定的方法,但现在我没有得到任何思想上的启发,卡住了,不知道如何进一步进行。
也不知道如何只反映该特定项目的变化。
你可以创建一个新的组件,代表一个菜单项目,让我们称它为MenuItemComponent.使用父子关系将'item'和'category'作为变量传递给这个组件(这可能会有帮助)。https:/angular.ioguidecomponent-interaction。),并添加一个变量,代表所选的顶点价格。为选择添加一个事件处理程序,这样它就会更新这个变量,所以我们的新组件将看起来像。
@Component({
selector: 'app-menu-item',
templateUrl: './menuitem.component.html'
})
export class MenuItemComponent {
@Input() item;
@Input() category;
private chosenToppingPrice = 0;
constructor(){}
onToppingSelect(event){
this.chosenToppingPrice = event.target.value;
}
}
而它的HTML会是这样的:
<mat-card *ngIf="item.category == category.name" class="itemcard">
<mat-card-header>
<mat-card-title>{{item.name}}</mat-card-title>
<mat-card-subtitle>{{item.category}}</mat-card-subtitle>
<span class="flex-spacer"></span>
<div>$ {{item.price_large + chosenToppingPrice}}</div>
</mat-card-header>
<mat-card-content>
<mat-form-field>
<mat-label>Extra Toppings</mat-label>
<mat-select multiple>
<mat-option *ngFor="let topping of toppings" [value]="topping.rate" (change)="onToppingSelect($event)">{{topping.name}}</mat-option>
</mat-select>
</mat-form-field>
</mat-card-content>
<span class="flex-spacer"></span>
<button mat-button color="primary"><i class="fa fa-plus-circle"></i> Add to Cart</button>
</mat-card>
最后,menu.component.html会是这样的:
<div fxFlex *ngFor="let category of categories">
<h3>{{category.name}}</h3>
<div *ngFor="let item of items">
<app-menu-item [item]="item" [category]="category"></app-menu-item>
</div>
</div>
这可能有点长,但这样你就可以单独操作每张卡的数据。
此外,我们不需要使用 *ngIf="item.category == category.name"
你可以简单地使用map函数。