如您所见,它的意思是将1乘以5,但我不知道如何,我尝试使用ngModel
进行操作,但这没用。
这是输入内容HTML中的代码,总价格必须是:
<input type="number" style="width:40px; float:right;" />
<br>
<hr>
<p style="float: left;">Total price:</p>
<p style="float: right;"> <b>€{{activeProduct.price * inputNum}}</b>,-</p>
这是我为产品制作的模型:
这是我的TypeScript文件中的代码:
import { Component, OnInit } from '@angular/core';
import { Product } from 'src/app/models/product';
@Component({
selector: 'app-tool-card',
templateUrl: './tool-card.component.html',
styleUrls: ['./tool-card.component.css']
})
export class ToolCardComponent implements OnInit {
public activeProduct: any;
public inputNum: number;
products: Product[] = [
new Product('Hammer', 'Hammer', 'Item used to hammer things', 'https://upload.wikimedia.org/wikipedia/commons/8/84/Claw-hammer.jpg', 1),
new Product('Saw', 'Hammer', 'I just saw a guy saying the n-word', 'https://media.screwfix.com/is/image//ae235?src=ae235/32045_P&$prodImageMedium$', 2),
new Product('Hit or miss', 'Hit or miss', 'I guess they never miss huh, mwah', 'https://pbs.twimg.com/media/Ds5mk0RU0AA1z_l.jpg', 5)
];
constructor() {
}
ngOnInit() {
}
public calculateTotal() {
this.activeProduct.price * this.inputNum;
}
public openModal(product): void {
// Copying object reference so we don't modify the original
this.activeProduct = Object.assign({}, product);
this.inputNum = 0;
}
}
答案 0 :(得分:0)
app.module.ts
文件中的导入数组中 app.module.ts
:
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [...],
imports: [
...
FormsModule
],
...etc
})
<div>
<p>{{ activeProduct.price }} </p>
<label for="amount">Amount</label>
<input type="number" (change)="calculateTotal() [(ngModel)]="activeProduct.numOfItems"/>
<br>
<hr>
<p style="float: left;">Total price:</p>
<p [(ngModel)]="totalCost">{{ totalCost }}</p>
</div>
export class AppComponent {
activeProduct: any = {
price: 12,
name: 'pizza',
numOfItems: 0
};
totalCost: number = 0;
constructor() {}
calculateTotal(): number {
return this.totalCost = this.activeProduct.numOfItems * this.activeProduct.price;
}
}
不是最优雅的方式,但是它将带您到达那儿。我认为最大的陷阱是FormsModule
答案 1 :(得分:0)
您尚未将输入框绑定到任何东西,请使用ngModel
<input type="number" [(ngModel)]="inputNum" style="width:40px; float:right;" />
或者如果您不想使用表单模块
<input type="number" (change)="inputNum = $event.target.value" style="width:40px; float:right;" />