首页 > 解决方案 > 在模板中使用表达式作为输入值

问题描述

<input 
    ngModel 
    name='quantity'
    placeholder='Quantity'
    type="number"
    class="form-control"
    pattern="^\d*(\.\d{0,2})?$" 
    required />

<input
    ngModel
    name='price'
    class="form-control"
    placeholder='Price'
    type="number"
    required />

<input 
    name='total' 
    class="form-control" 
    type="number" 
    [value]='addRowForm.value.quantity * addRowForm.value.price' />

我有三个输入字段Quantity、Price、Total,数量和价格的乘积应该显示在 Total 字段中,我可以在 Typescript 代码中执行此操作,但我想知道是否有一个简单的解决方案可以仅在模板中执行此操作。

我已经尝试过了,但它不起作用。

[value]='addRowForm.value.quantity * addRowForm.value.price'

标签: angular

解决方案


[(ngModel)]在字段中添加。

试试这样:

工作演示

<input [(ngModel)]="quantity" name='quantity' placeholder='Quantity' type="number" class="form-control" pattern="^\d*(\.\d{0,2})?$" required />

<input [(ngModel)]="price" name='price' class="form-control" placeholder='Price' type="number" required />

<input name='total' class="form-control" type="number" [(ngModel)]='quantity * price' />

你也可以像这样使用它:

演示

TS:

newRowDetails = {}

模板:

<input [(ngModel)]="newRowDetails.quantity" name='quantity' placeholder='Quantity' type="number" class="form-control" pattern="^\d*(\.\d{0,2})?$" required />

<input [(ngModel)]="newRowDetails.price" name='price' class="form-control" placeholder='Price' type="number" required />

<input name='total' class="form-control" type="number" [(ngModel)]='newRowDetails.quantity * newRowDetails.price' />

推荐阅读