简体   繁体   English

使用 angular 双向数据绑定 angular 7 将字符串值绑定到复选框切换

[英]Bind a string value to a checkbox toggle using angular two-way data binding angular 7

<div class="form-group col-12 col-md-6">
     <label class="mb-1 mr-2">
         Status 
     </label> 
     <div class="custom-control custom-checkbox-toggle">
          <input type="checkbox" class="custom-control-input" id="status"
              [(ngModel)]="question.conditions[0].status">
                                    
          <label class="custom-control-label" for="status"></label>
      </div>  
 </div>
`
Conditions: [
  {
    "status": "",
    "questionId": {
      "eq": "6012e7378d65710016832916"
    },
    "selects": {
      "in": [
        "6012e7eb8d65710016832b61",
        "6012e7eb8d65710016832b65"
      ]
    }
  }
]

I want to binding my data is 'active' ||我想绑定我的数据是“活动的”|| 'disabled' to this toggle when i switching it.But it not works and crashing the page.My required is binding it with string value(not binding boolean value).当我切换它时“禁用”到此切换。但它不起作用并崩溃页面。我需要将它与字符串值绑定(不绑定 boolean 值)。

Add [checked] attribute as below code, so that it will bind the property.添加如下代码的[checked]属性,以便绑定属性。

   <input type="checkbox" class="custom-control-input" id="status" 
        [checked]="question.Conditions[0].status != '' || question.Conditions[0].status != 'true' ?  true: false "
            [(ngModel)]="question.Conditions[0].status">

There is something which is missed from json, Conditions to conditions (if not typo) json 遗漏了一些东西,条件条件(如果不是错字)

Happy Coding.. :)快乐编码.. :)

Try using (change) and bind your value there尝试使用(更改)并在那里绑定您的值

<input type="checkbox" class="custom-control-input" id="status"
            [(ngModel)]="question.Conditions[0].status"  
(change)="question.Conditions[0].status = question.Conditions[0].status ? 'active' : 'disable';">

You can assign the value on changing of the checkbox您可以在更改复选框时分配值

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

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