问题
In my project I want to create an invoice. In this invoice I calculate value with a function get subtotal(){}
, totally work good. Now, If I change this subtotal, for example, I want to make a discount from 100 to 90.
I've tried this code but it does not work. Please, can you suggest me how to solve this issue? Html code:
<div class="input-field col s2" style="float: right;">
<input formControlName="Subtotal " id="Subtotal " [value]="subtotal " type="number" class="validate" (change)="updateForm($event)">
</div>
ts code:
updateForm(event) {
console.log(event)
let amountpaidd = event.target.value
this.addsale['controls']['Subtotal '].setValue(amountpaidd );
}
onaddsale() {
let sale = this.addsale.value;
sale.Subtotal = this.subtotal;
let newSale = new Sale(sale);
console.log(newSale)}
get subtotal() {
return this.products
.map(p => p.p_Unit_price * p.p_Quantity)
.reduce((a, b) => a + b, 0);
}
Thank you!
Update:
this.addsale = this.formbuilder.group({
'Subtotal ': new FormControl('', Validators.required),
'products': this.formbuilder.array([]),
});
回答1:
If you need to have a precalculated value in there, then just set the value of the control. Do not use the view (HTML) to pass the value back and forth.
First, create your form using the form builder.
Then, set the value from subtotal using this.addSale.controls.Subtotal.setValue(this.subtotal)
. Do this whenever the subtotal changes.
ngOnInit() {
this.service.productList.subscribe(productList => {
this.products = productList;
this.addsale.controls.Subtotal.setValue(this.subtotal)
});
}
Do not use sale.Subtotal = this.subtotal
.
let sale = this.addsale.value
already does that.
in your view, use the basic reactive form binding.
<input formControlName="Subtotal" id="Subtotal" type="number" class="validate">
Your value should get updated whenever you call the setValue(this.subtotal)
The user can overwrite the value of course. But it may get overwritten if you add more products or so. If you want to prevent that, you should watch if user has done that and prevent updating the value with new subtotal anymore.
Working demo based on demo you provided in comment.
来源:https://stackoverflow.com/questions/50240387/i-cant-submit-a-value-input-when-use-change