Angular2登录页点击登录时手机号为undefined问题求助
解决Angular2登录时手机号为undefined的问题
我来帮你排查这个问题哈,看你的代码,主要有几个地方可能导致手机号变成undefined,咱们一步步来解决:
核心问题1:loginIntData对象未初始化
Angular的双向绑定[(ngModel)]需要绑定到一个已存在的对象属性上。如果你的组件类里只是声明了loginIntData: LoginInterface;但没有初始化,那loginIntData本身就是undefined,mobile属性自然也会是undefined。
修复方法
在组件类里初始化这个对象:
// 先导入你的LoginInterface import { LoginInterface } from './path-to-your-interface'; // 组件类中初始化 loginIntData: LoginInterface = { mobile: '', otp: '' };
核心问题2:原生DOM事件与Angular事件冲突
你的SEND OTP按钮同时使用了原生的onclick="sendOTP()"和Angular的(click)="OnSendOTP(loginIntData)":
- 如果
sendOTP()这个函数没有在全局定义,浏览器会报错,直接中断Angular的事件执行; - 就算函数存在,原生事件也可能干扰Angular的变更检测,导致数据无法正确同步。
修复方法
删掉原生的onclick属性,只用Angular的(click)绑定:
<button class="sendbtn btn btn-default submit" id="otpbtn" (click)="OnSendOTP()">SEND OTP</button>
同时修改组件类的方法,直接使用组件内的loginIntData,不用传参:
OnSendOTP() { this._httpService.OnOtp(this.loginIntData).subscribe ( data => { this.loginIntData = data; // 这里可以加个状态标记,控制按钮显示隐藏 this.isOtpSent = true; }, error => alert("error"+error), () => console.log("received OTP") ); }
核心问题3:原生onkeyup事件的问题
你用了onkeyup="validateNumber()"和onkeyup="otpValue()"调用全局函数,但Angular里应该用组件类的方法+Angular事件绑定语法(keyup),否则会绕过Angular的变更检测,导致数据不同步。
修复方法
把原生事件换成Angular绑定:
<input type="tel" id="mob" name="phone" [(ngModel)]="loginIntData.mobile" class="form-control" (keyup)="validateNumber()" placeholder="Mobile" required /> <input type="password" id="otp" name="otp" [(ngModel)]="loginIntData.otp" class="form-control" (keyup)="otpValue()" placeholder="Enter OTP" required [disabled]="!isOtpSent" />
然后在组件类里实现这两个方法:
validateNumber() { // 你的手机号验证逻辑,比如检查长度是否合规 // 示例:if (this.loginIntData.mobile.length === 10) { ... } } otpValue() { // OTP输入后的逻辑,比如检查OTP长度 }
额外优化建议
- 输入类型用
type="tel"比type="phone"更标准,能唤起移动端数字键盘; - 按钮的
class属性不要重复写多个,合并成一个即可(比如class="sendbtn btn btn-default submit"); - 用Angular的
[hidden]或*ngIf控制按钮显示隐藏,不要用原生JS操作DOM,保证数据和视图同步:
<button class="sendbtn btn btn-default submit" id="otpbtn" (click)="OnSendOTP()" [hidden]="isOtpSent">SEND OTP</button> <button id="loginbtn" class="btn btn-default submit" (click)="OnLogin()" [hidden]="!isOtpSent">LOGIN</button>
组件类里加个状态变量:
isOtpSent = false; // 默认隐藏登录按钮
修改后的完整登录方法
OnLogin() { console.log("Inside login method"); console.log("mobile: " + this.loginIntData.mobile); console.log("otp: " + this.loginIntData.otp); this._httpService.Onvalidate(this.loginIntData).subscribe ( data => this.loginIntData = data, error => alert("error"+error), () => console.log("user logged in", this.loginIntData) ); }
做完这些修改后,loginIntData.mobile就能正确获取到输入框的值,不会再出现undefined的情况啦~
内容的提问来源于stack exchange,提问作者Aswathi L
相关产品推荐
相关产品推荐

