javascript - 将端点的值分配给复选框
问题描述
我正在尝试将从端点获得的值分配给复选框
这是对象
{sendOtpEmail: true}
我必须在端点响应中进行一些搜索,以区分是电子邮件值返回还是手机值返回
这是我的代码
TS
otpCellValue: any;
otpEmailValue: any;
getOTPChannel() {
this._loader.start();
this._subscriptions.push(this._corpService.getOTPChannel().subscribe((resp) => {
//get endpoint object
console.log(resp);
//get endpoint object parameter name
let keyNames = Object.keys(resp);
console.log(keyNames[0]);
//check for email keyword
if(keyNames[0].includes('Email')) {
console.log(resp.sendOtpEmail);
//get value
if(resp.sendOtpEmail == true) {
//email value is true so the otpEmailValue checkbox should be checked however it is not
this.otpEmailValue = 1;
this.otpCellValue = 0;
} else {
this.otpEmailValue = 0;
this.otpCellValue = 0;
}
}
this._loader.stop();
}, (error) => {
this._loader.stop();
this._errorService.openErrorPopup('Failed to get OPT channel.');
}));
}
HTML
<input type="radio" name="1" id="1" class="with-gap" [(ngModel)]="otpCellValue" [(value)]="otpCellValue">
<input type="radio" name="2" id="2" class="with-gap" [(ngModel)]="otpEmailValue" [(value)]="otpEmailValue">
我在上面的代码中添加了注释来说明我在做什么
所以现在我很困惑为什么不选中电子邮件复选框。有任何想法吗?
解决方案
这些不是复选框,而是单选按钮。假设您确实需要单选按钮(在您的情况下看起来像它,因为它可能是其中之一),有一些事情需要做。
与其使用 2 个属性来指示选择了哪个选项,不如使用 1 个属性来实现该目的。
所以
this.otpEmailValue = 1;
this.otpCellValue = 0;
变成
this.contact = 'email'; // This line is now equivalent to the ones above
在模板中,单选按钮输入需要具有相同的名称,以便它们作为 1 个输入而不是 2 个输入,因为毕竟我们只希望选择 1 个选项。该ngModel
指令现在指向我们要绑定的值,在我们的例子中是contact
. 最后,该值应该是静态的。当绑定的属性的值ngModel
与其中一个单选按钮的值匹配时,它将选择它。
因此,在所有这些更改之后,我们得到以下内容。
<input type="radio"
name="contact-option"
id="1"
class="with-gap"
[(ngModel)]="contact"
value="cell"> Cell
<input type="radio"
name="contact-option"
id="2"
class="with-gap"
[(ngModel)]="contact"
value="email"> Email
推荐阅读
- css - 如何更改复选框的选中颜色?
- ios - 十进制数精确性错误是什么异常?
- c++ - 如何通过行尾将字符串拆分为向量
- python - 有人可以帮我解决使用 nltk word_tokenize 函数的错误吗?
- angular - 当检查数组中的重复值时,它显示未定义
- twitter-bootstrap - 在选择下拉列表旁边垂直对齐文本(带引导程序)
- razorpay - 无法创建超过 50,000 印度卢比的订单 - Razorpay
- ios - 如何从 XCode 中删除 Swift 包?
- php - 错误“根 composer.json 需要 php ^7.3 但您的 php 版本 (8.0.0) 不满足该要求”
- github-actions - 通过 GitHub Actions 将 Python 包发布到 AWS CodeArtifact