Angular 2: 动态生成的<select>标签计算价格
创始人
2024-10-15 16:32:30
0

下面是一个使用Angular 2动态生成

总价: {{ totalPrice }}

` }) export class AppComponent { products = [ { name: '商品A', price: 10 }, { name: '商品B', price: 20 }, { name: '商品C', price: 30 } ]; selectedProduct: any; quantity: number = 1; totalPrice: number = 0; calculatePrice() { if (this.selectedProduct) { this.totalPrice = this.selectedProduct.price * this.quantity; } else { this.totalPrice = 0; } } }

在模板中,使用Angular的双向数据绑定 [(ngModel)] 来实现选项的选择和数量的输入。当选择的商品或数量发生变化时,调用 calculatePrice() 方法来计算总价。使用 *ngFor 指令循环遍历 products 数组,动态生成

最后,在主模块中加载组件:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

这样就可以动态生成