【问题标题】:pass id of the selected checkbox(which areloaded with ngFor) when it is checked选中复选框时传递所选复选框的 ID(使用 ngFor 加载)
【发布时间】:2020-01-10 11:55:34
【问题描述】:
       <form name="check-boxes">
          <div *ngFor="let quest of noOfQuestions">
            <div class="form-check form-check-inline" *ngFor="let ans of noOfAnswers">
              <label class="form-check-label">{{ans}}
               <input class="form-check-input" type="checkbox" name="{{quest}}" id="{{quest}}{{type}}" value="{{ans}}"  (change)="getAnswers(id)"> 
              <span class="form-check-sign"></span>
             </label>
            </div>
          </div>
      </form>

angular componentx.html 中的示例输出:

此代码根据提供的 noOfQuestions 和 noOfAnswers 生成一组复选框。当检查复选框时,我想将复选框的特定ID传递到'getanswer'的功能。在 ts 文件中传递的参数 'id' 值,称为未定义。 getAnswer() 传递选中复选框的 id 的参数应该是什么???

【问题讨论】:

  • 对象quest有变量吗?它是什么类型的?也许你可以做(change)="getAnswers(quest.id)"
  • 任务只是一个数字
  • id="{{quest}}{{type}}"这是你的身份证对吧?
  • 是的,它是单选按钮的 ID
  • @AnupamaThathsarani 您也可以使用这种方法。 Click

标签: html angular radio-button ngfor


【解决方案1】:

如果你通过了 $event:

(change)="getAnswers($event)"

那么您应该可以通过event.target 访问您的打字稿文件中的该输入元素,但检查是否已检查也很重要:

getAnswers(event) {
   if (event.target.checked) {
      console.log('checked: ' + event.target.id);
   } else {
      console.log('unchecked: ' + event.target.id);
   }
}

【讨论】:

  • 当使用 $event 作为参数时,它工作正常谢谢
  • 我知道,我现在也在学习 angular :) 如果您认为答案正确,那就太好了。
【解决方案2】:

这样做。

在你的 html 中

(change)="getAnswers(quest,type)"

在你的打字稿中

//I have no idea about the types of parameters you used.
getAnswers(quest: any, type: any) 
{
    console.log('Id: ' + `${quest}${type}`);
}

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2014-06-20
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2011-05-06
    • 2019-01-14
    • 1970-01-01
    相关资源
    最近更新 更多