简体   繁体   English

如何检索 mat-checkbox 值

[英]How to retrieve mat-checkbox value

I am a beginner with angular material.我是 angular 材料的初学者。 I have written this code so far:到目前为止,我已经编写了这段代码:

 Answer { id: string; content: string; }
 <section *ngFor="let opt of step.answers"> <mat-checkbox [checked]="opt.id" (change)="check($event)"> <p [innerHTML]="opt.content"> </p> </mat-checkbox> </section>

I still can't figure out how to retrieve the id for every option selected in every stepper and collect them in array我仍然无法弄清楚如何检索每个步进器中选择的每个选项的 id 并将它们收集到数组中

so this is the solution I've found, it's close to @Çağrı proposition but I changed few things since "event" has an attribute checked that I can use without needing to use a variable to save the value of "isChecked"所以这是我找到的解决方案,它接近@Çağrı 命题,但我改变了一些东西,因为“事件”有一个属性检查,我可以使用它而不需要使用变量来保存“isChecked”的值

 check(event, opt, userResponse) { var rep = []; if (event.checked === true) { userResponse.push(opt); } if (event.checked === false) { var index: number = userResponse.indexOf(opt); userResponse.splice(index, 1); } }
 <section *ngFor="let opt of step.answers" > <mat-checkbox (change)="check($event,opt,step.userResponse)"> <p [innerHTML]="opt.content"> </p> </mat-checkbox> </section>

in [checked] condition u can't put id.在 [检查] 条件下,您不能输入 id。 It is true false condition.这是真假条件。 U should add one attribute more of step.answers model which calls ischecked whose initial value is false. U 应该多添加一个属性 step.answers model 调用 ischecked 其初始值为 false。 and create global array called choosenanswers,and write并创建名为 choosenanswers 的全局数组,并编写

Answer {
    id: string;
    content: string;
    ischecked:boolean=false;
}

then然后

 <section *ngFor="let opt of step.answers">
         <mat-checkbox [checked]="opt.ischecked" (change)="check($event)">
              <p [innerHTML]="opt.content"> </p>
          </mat-checkbox> 
    </section>

then in check event in components然后在组件中检查事件

  check(event){
      this.choosenanswers=[];
      this.step.answers.foreach(x=>{if(x.ischecked){ this.choosenanswers.push(x.id);}})
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM