Angular中不使用模板/响应式表单创建表单及取值问题
问题解答
一、模板驱动表单无法获取值的原因
你的复选框缺少ngModel指令,Angular模板驱动表单需要通过ngModel将控件与表单实例关联,否则creditForm无法识别该控件。修改代码如下:
<form #creditForm="ngForm"> <input id="storeCredit" name="storeCredit" type="checkbox" class="form-check-input" [(ngModel)]="isUseCredit" /> <label class="form-check-label" for="storeCredit"> You have {{ user.store_credit | float | currencyFormat : currency }} of store credit </label> </form> FORM {{ creditForm | json }}
同时在组件类中定义对应变量:
isUseCredit = false;
修改后creditForm就能正常捕获storeCredit的勾选状态。
二、不使用表单实现需求的方案
既然不需要将值提交到后端,完全可以脱离Angular表单模块,通过变量绑定或事件监听实现储值扣除逻辑:
方案1:双向绑定[(ngModel)]
<input id="storeCredit" type="checkbox" class="form-check-input" [(ngModel)]="isUseCredit" /> <label class="form-check-label" for="storeCredit"> You have {{ user.store_credit | float | currencyFormat : currency }} of store credit </label> <!-- 实时展示计算后的总价 --> <p>总价:{{ totalPrice - (isUseCredit ? user.store_credit : 0) | currencyFormat : currency }}</p>
组件类中定义基础变量:
isUseCredit = false; totalPrice = 100; // 替换为实际总价变量
方案2:(change)事件监听
<input id="storeCredit" type="checkbox" class="form-check-input" (change)="onCreditToggle($event)" /> <label class="form-check-label" for="storeCredit"> You have {{ user.store_credit | float | currencyFormat : currency }} of store credit </label> <p>总价:{{ finalPrice | currencyFormat : currency }}</p>
组件类中处理状态切换与总价计算:
finalPrice = 100; totalPrice = 100; // 替换为实际总价变量 onCreditToggle(event: Event) { const isChecked = (event.target as HTMLInputElement).checked; this.finalPrice = isChecked ? this.totalPrice - this.user.store_credit : this.totalPrice; }
以上两种方案都无需依赖表单模块,直接通过变量或事件即可实现勾选状态监听与总价调整。
内容的提问来源于stack exchange,提问作者aRtoo
相关产品推荐
相关产品推荐

