首页 文章

Angular,绑定输入类型Checkbox,默认选中

提问于
浏览
1

我正在使用带有复选框的Angular 5应用程序 . 我有来自数据库的数据,然后映射到javaScript对象 . 我正在尝试配置“已选择”值,但无法执行此操作 . 在我的结果中,我检查了所有应该是的盒子 .

在下面的代码中,选项:[] - >'optionSelected'定义,如果选择值为true或false,

生成的模式如下;

enter image description here

模板

<div *ngSwitchCase="'checkbox'"> <small>checkbox</small>
       <div *ngFor="let opt of question.options" >
            <label class="container-vertical"> {{opt.value}}
                <input type="checkbox" [formControlName]="question.key" [name]="opt.name" [value]="opt.key" [checked]="opt.optionSelected" /> 
                <span class="checkmark2"></span>
            </label>
       </div>      
 </div>

也尝试使用ngModel,因为在我的组件中,属性'value'包含所选键的id,但最终结果仍然检查所有框

<input type="checkbox" [formControlName]="question.key" [name]="opt.name" [value]="opt.key" [(ngModel)]="question.value" />

组件

else  if(questionElementType=="checkbox")
 {
   let _checkBox = new CheckBoxQuestion ({
     consultationId: questionsList[key].consultationId,
     questionId: questionsList[key].questionId,
     questionElementType: questionsList[key].questionElementType[0].title,           
     questionType: questionsList[key].questionType,
     title:questionsList[key].title,
     displayId: questionsList[key].displayId,
     key: questionsList[key].questionId,     
     value: questionsList[key].answer.length<=0? null : questionsList[key].answer[0].answerValue.toLowerCase(),
     label: questionsList[key].title, 
     order: 7,
     options: questionsList[key].answerOptions.map(function(item){
       return {"name": item.ReferenceKey, "key": item.preDefineAnswerOptionId, "value": item.text, "optionSelected": item.preDefineAnswerOptionId==questionsList[key].answer[0].answerValue? "true": "false"}
    }),
   });

     this.mappedQuestions.push(_checkBox);
 }

1 回答

  • 2

    如果要取消选中该复选框,则其 [value] 绑定必须是假的 .

    "true""false" 都是非空字符串,这意味着它们的计算结果为 true .

    "false" 转换为 false ,它将按预期工作 .

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `
    <input type="checkbox" [(ngModel)]="checkbox1" /> "true"
    <input type="checkbox" [(ngModel)]="checkbox2" /> "false"
    <input type="checkbox" [(ngModel)]="checkbox3" /> true
    <input type="checkbox" [(ngModel)]="checkbox4" /> false
      `,
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      checkbox1 = 'true';
      checkbox2 = 'false';
      checkbox3 = true;
      checkbox4 =  false;
    }
    

    checkbox example

    Live demo

相关问题