下面是一个使用Angular 2动态生成
首先,在组件类中定义一个数组来存储商品信息和价格,以及一个变量来存储选中的商品和数量:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
商品选择
总价: {{ 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 { }
这样就可以动态生成