I’m trying to add a value of 100
when it’s set to true and 0
when it’s set to false.
It is currently able to add Rs 100 when set to true
but it doesn’t revert to 0
when I set it back to false
. Where am I doing wrong?
Here’s the HTML:
<label>Add Rs 100</label>
<select class="form-select" name="casualty" id="casualty" [(ngModel)]="opd.casualty" (ngModelChange)="addBillingOtherCharges($event)">
<option value="false">No</option>
<option value="true">Yes</option>
</select>
<input type="number" name="totalAmt" id="totalAmt" [(ngModel)]="billingItem.totalAmount" (ngModelChange)="totalAmountEdited()">
Here’s the TS file
addBillingOtherCharges(e:Event){
if(e){
this.billingItem.otherAmountKey = "Casualty";
this.billingItem.otherAmountValue = 100
}else{
this.billingItem.otherAmountKey = "";
this.billingItem.otherAmountValue = 0
}
this.calculateTotalAmount()
}
calculateTotalAmount(){
this.billingItem.totalAmount = 0
this.billingItem.totalAmount = (this.billingItem.otherAmountValue==undefined?0:this.billingItem.otherAmountValue)+(this.billingItem.amount||0) - (this.billingItem.discountAmount||0) || 0
}
totalAmountEdited(){
this.billingItem.amount = 0;
this.opd.casualty = false;
this.billingItem.discountAmount = 0;
}
Try property binding with ngValue
instead of the property value
, so it will be [ngValue]
.
In the old method value
will store a string 'true'
. Because attributes in html are always taken as string.
In the new method [ngValue]
will store a boolean true
The string 'false'
will evaluate to true in a if condition.
<label>Add Rs 100</label>
<select class="form-select" name="casualty" id="casualty" [(ngModel)]="opd.casualty" (ngModelChange)="addBillingOtherCharges($event)">
<option [ngValue]="false">No</option>
<option [ngValue]="true">Yes</option>
</select>
<input type="number" name="totalAmt" id="totalAmt" [(ngModel)]="billingItem.totalAmount" (ngModelChange)="totalAmountEdited()">
Stackblitz Demo
2
The easy way: accept that it’s a string, and instead of
if(e) { // do stuff
do
if(e === 'true') { // do stuff
The neater, more reusable way (if you need it at all) would be to write a custom form control, which would have the model as boolean, instead of string. Because by default input’s model is string.
(Here’s the official recipe for creating custom form controls:)
https://blog.angular-university.io/angular-custom-form-controls/