Html 选中复选框时,通过所选复选框(已加载ngFor)的id {{ans}}

Html 选中复选框时,通过所选复选框(已加载ngFor)的id {{ans}},html,angular,radio-button,ngfor,Html,Angular,Radio Button,Ngfor,angular componentx.html中的示例输出: 此代码根据提供的noOfQuestions和noofanswer生成一组复选框。选中复选框时,我想将复选框的特定id传递给函数“getAnswer”。ts文件中传递的参数“id”值称为未定义。要传递选中复选框的id,getAnswer()的参数应该是什么?如果传递$event: <form name="check-boxes"> <div *ngFor="let quest of

angular componentx.html中的示例输出:


此代码根据提供的noOfQuestions和noofanswer生成一组复选框。选中复选框时,我想将复选框的特定id传递给函数“getAnswer”。ts文件中传递的参数“id”值称为未定义。要传递选中复选框的id,getAnswer()的参数应该是什么?

如果传递$event:

       <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>
然后,您应该可以通过
event.target
访问typescript文件中的输入元素,但检查是否选中也很重要:

(change)="getAnswers($event)"
像这样做

在html中

getAnswers(event) {
   if (event.target.checked) {
      console.log('checked: ' + event.target.id);
   } else {
      console.log('unchecked: ' + event.target.id);
   }
}
在你的打字稿中

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

对象
quest
是否有任何变量?它是什么类型的?也许你可以做
(change)=“getAnswers(quest.id)”
quest只是一个数字
id=“{{quest}}{{type}}}”
这是你的id,对吗?是的,这是收音机的idbutton@AnupamaThathsarani您也可以使用这种方法。当使用$event作为参数时,它工作得很好。谢谢,我知道,我现在也在学习:)如果您认为答案正确,请将其标记为正确。
//I have no idea about the types of parameters you used.
getAnswers(quest: any, type: any) 
{
    console.log('Id: ' + `${quest}${type}`);
}