Angular5中实现按钮初始禁用、输入长度为10时启用的问题
Angular5 按钮根据输入框长度启用/禁用解决方案
问题核心:你使用了type="number"的输入框,[(ngModel)]绑定的MSISDN_Value是数字类型,数字没有length属性,直接判断MSISDN_Value.length !==10时,length会返回undefined,导致条件始终为true,按钮一直处于禁用状态。
以下是两个可行解决方案:
方案一:改用text类型输入框(推荐)
将输入框类型改为text,同时限制仅能输入数字、最大长度10,这样绑定的变量为字符串,可直接通过length判断:
<div class="form-group"> <label for="MSISDN_Value" class="m-r-10">MSISDN:</label> <input type="text" onkeypress="return /[0-9]/.test(event.key)" maxlength="10" [(ngModel)]="MSISDN_Value" id="MSISDN_Value" name="MSISDN_Value" class="form-control display-inline-block width70p m-b-5"> </div> <div class="form-group"> <button class="btn btn-primary m-l-65" type="submit" [disabled]="MSISDN_Value?.length !== 10">Search</button> </div>
onkeypress限制仅能输入数字maxlength="10"直接限制输入长度,避免多余输入MSISDN_Value?.length用可选链处理初始值为undefined的情况,避免报错
方案二:保留number类型输入框
如果必须使用type="number",需要把数字转成字符串后再判断长度,同时处理初始值为undefined的情况:
<div class="form-group"> <label for="MSISDN_Value" class="m-r-10">MSISDN:</label> <input type="number" onkeyPress="if(this.value.length === 10) return false;" [(ngModel)]="MSISDN_Value" id="MSISDN_Value" name="MSISDN_Value" class="form-control display-inline-block width70p m-b-5"> </div> <div class="form-group"> <button class="btn btn-primary m-l-65" type="submit" [disabled]="!(MSISDN_Value && MSISDN_Value.toString().length === 10)">Search</button> </div>
MSISDN_Value &&先判断变量是否存在,避免undefined.toString()报错- 转成字符串后再判断长度是否为10,取反后作为禁用条件
内容的提问来源于stack exchange,提问作者Anmol Girdhar
相关产品推荐
相关产品推荐

