【发布时间】:2018-10-14 23:12:49
【问题描述】:
我在我的项目中运行ng build --prod。
我发现是这个错误:
src\app\components\xxxx\xxxx.component.html(116,100): : 无法分配 到 'total' 因为它是一个常量或只读属性。
在这一行我有这个代码:
<input formControlName="total" id="total" type="text" class="validate" [(ngModel)]="total">
我使用了[(ngModel)]="total" --> 因为我希望即使不修改它也能保存该值。如果我使用[value]="total",则此错误不存在,但如果我不修改,我的值不会保存。
这个总数是我通过 ts 中的这个函数得到的。这是只读的
get total() {
return this.products
.map(p => p.p_Unit_price * p.p_Quantity)
.reduce((a, b) => a + b, 0);
}
这个总数,显示所有产品的总数。
如何修改这段代码,可以正常工作吗?
编辑:
HTML代码:
<form [formGroup]="addsale" (ngSubmit)="onaddsale()">
<table align="center" class="table table-bordered table-hover">
<thead>
<tr style="color:black;">
<th>p_Product_type_id</th>
<th>p_product_id</th>
<th>p_Unit_price</th>
<th>p_Quantity</th>
</tr>
</thead>
<tbody>
<tr class="group" *ngFor="let item of products">
<td>{{item.p_Product_type_id}}</td>
<td>{{item.p_product_id}}</td>
<td>{{item.p_Unit_price}}</td>
<td>{{item.p_Quantity}}</td>
</tr>
</tbody>
</table>
<br>
<br>
<div class="row">
<div class="input-field col s2" style="float: right;">
<label for="total">Total {{total}} ALL</label>
<input formControlName="total" id="total" type="text" class="validate" [value]="total" [(ngModel)]="total">
</div>
<div class="input-field col s2" style="float: right;">
<label for="total">Subtotal</label>
<input formControlName="Subtotal" id="Subtotal" type="text" class="validate" [value]="total" [(ngModel)]="total">
</div>
</div>
<hr>
<br>
<div id="add_homebox_button_container" class="row" style="float: right;">
<button id="add_client_button" type="submit" class="btn waves-effect waves-light">
Register
</button>
</form>
Ts 代码:
export class component implements OnInit {
constructor(.............
) {
this.addsale = this.fb.group({
'Subtotal': new FormControl('', Validators.required),
'products': this.fb.array([]),
'total': new FormControl('', Validators.required),
});
}
ngOnInit() {
this.allproducts();
allproducts() {
this.products = this.ps.getProduct();
}
onaddsale() {
this.areWeWaiting = true;
let sale = this.addsale.value
sale.products = this.products
let newSale = new Sale(sale);
this.ws.saleitemcreate(newSale).subscribe(
result => {
if (result === true) {
Materialize.toast('Successfully', 4000);
} else {
this.areWeWaiting = false;
}
},
error => {
this.areWeWaiting = false;
}
);
}
get total() {
return this.products
.map(p => p.p_Unit_price * p.p_Quantity)
.reduce((a, b) => a + b, 0);
}
}
【问题讨论】:
-
你需要add a setter
标签: angular typescript angular5 readonly