【问题标题】:How to make a checkbox check dynamically based on a array of values in angular 6?如何根据角度 6 中的值数组动态进行复选框检查?
【发布时间】:2019-03-13 22:16:00
【问题描述】:

我的ajax调用结果如下,

data : 
  0: {Address: "Delhi", EmailID: "bravo123@gmail.com", MobileNo: 
"9876543210", Name: "Bravo", Date: "04/06/2008", …}
1: {Mode: "0"}
2: {Mode: "1"}
3: {Mode: "2"}
4: {Mode: "3"}
5: {Mode: "4"}

我可以使用显示数据,

 <p *ngIf="details">{{ details[0]?.EmailID }}</p>

但我得到的模式是复选框的值。如何根据从 ajax 调用返回的值选择复选框。

我的复选框代码html如下:

   <div class="custom-checkbox">
     <input type="checkbox" class="custom-control-input 
       [attr.id]="mode[i].id" [name]="mode[i].name"
       [checked]="(mode && (mode.indexOf(mode[i].id) !== -1))">
     <label class="custom-control-label" [attr.for]="mode[i].id"> 
       {{mode[i].name}}</label>
   </div>
   <div class="custom-control custom-checkbox custom-control-inline">
     <input type="checkbox" class="custom-control-input" 
       [attr.id]="mode[i+1].id" [name]="mode[i+1].name"
       [checked]="(mode && (mode.indexOf(mode[i+1].id) !== -1))">
     <label class="custom-control-label" [attr.for]="mode[i+1].id"> 
       {{mode[i+1].name}}</label>
   </div>

我的 ts 文件:

public mode = [
  { id: 0, name: 'Select All' },
  { id: 1, name: 'aaa' },
  { id: 2, name: 'bbb' },
  { id: 3, name: 'cccc' },
  { id: 4, name: 'dddd' },
];

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: html angular checkbox angular6


    【解决方案1】:

    你需要这样的东西:

    <input type="checkbox" value="item.id" [attr.checked]="fooData.mode === item.id ? true : null" />
    

    在此处注意 null

    我创建了一个小的Working Demo,就像你的代码一样。

    Updated Demo 带有数据数组。

    【讨论】:

    • 非常感谢您的回复@SyedAliTaqi 对于单一价值,我能够做到。但是,如果我有更多返回的值,我该如何检查该复选框?你能帮帮我吗?
    • 更多来自服务的价值?
    • Yes Yes @SyedAliTaqi 就像它返回三个值 aaa、bbb、ccc。我怎样才能使它们全部被选中?
    • 是的,但我需要在一行中检查三个值。例如,我们有三行 knw?
    • 非常感谢。这就是我一直在寻找的。再次感谢
    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2020-08-23
    • 2021-02-12
    • 2019-01-17
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多