首页 > 解决方案 > 将端点的值分配给复选框

问题描述

我正在尝试将从端点获得的值分配给复选框

这是对象

{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">

我在上面的代码中添加了注释来说明我在做什么

所以现在我很困惑为什么不选中电子邮件复选框。有任何想法吗?

标签: javascriptangular

解决方案


这些不是复选框,而是单选按钮。假设您确实需要单选按钮(在您的情况下看起来像它,因为它可能是其中之一),有一些事情需要做。

与其使用 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

演示


推荐阅读