我试图根据 angular 8 中的值禁用和启用复选框

I an trying to disable and enable checkbox based on value in angular 8

这是我的代码

我有这样的列表数组:这是 getCall。 ktsession = [ {"presenter":"Bharath","topic":"Angular","status":"scheduled","emailId":"bharathkumar@gmail.com"}, {"presenter": "Sayyad","topic":"Angular","status":"organized","emailId":"raheemsayyad@gmail.com"},{"presenter":"Kanchan","topic ":"APS","status":"已安排","emailId":"kanchanubey@gmail.com"} ];

<tr *ngFor = "let ktsession of ktsessions >

  <td ><input type="checkbox" [disabled]='disabled'></td>
</tr>

TS代码:

getktsession(){   
    this.service.getKtsession().subscribe(data =>{
      console.log('get', data);
      this.ktsessions = data;
      this.ktsessions.find(user => {
     
       if(user.presenter ==="Kanchan"){
       this.disabled = true
} else {
this.disabled = false;
}
        
      });
    });
  }

这里有几个问题。

  1. <tr *ngFor = "let ktsession of ktsessions > - ktsessions
  2. 后缺少收盘价
  3. <td ><input type="checkbox" [disabled]='disabled'></td> - [disabled]='disabled' 应该是 [disabled]="ktsession.disabled"。每个复选框实例都需要有自己的 disabled 属性。 [disabled]='disabled' 将每个复选框的 disabled 属性 设置为组件 class 实例的 disabled 属性 而不是复选框实例。
  4. this.ktsessions.find(user => { - Array#find is not an appropriate method to use here, even though it happens to work since you're not returning anything from the callback function and it will therefore iterate the entire array. Array#find is for searching an array for an element that matches the specified criteria and returning that element, not for iterating over an array and setting properties on each element, which is what you're doing here. Array#forEach 是合适的方法。
  5. this.disabled = truethis.disabled = false - 它们在组件 class 实例上设置 disabled 属性(这是 this 所指的到),但您需要做的是在每个 user 实例上设置 disabled 属性:user.disabled = trueuser.disabled = false.

因此您的模板应如下所示:

<tr *ngFor="let ktsession of ktsessions">
  <td>
    <input type="checkbox" [disabled]="ktsession.disabled" /> <!-- reference "ktsession.disabled" instead of "disabled" -->
    {{ ktsession.presenter }}
  </td>
</tr>

你的 subscribe 应该看起来像这样:

this.getKtsession().subscribe((data) => {
  this.ktsessions = data;
  this.ktsessions.forEach((user) => { // <-- use forEach, not find
    if (user.presenter === 'Kanchan') {
      user.disabled = true; // <------------ set user.disabled, not this.disabled
    } else {
      user.disabled = false; // <----------- set user.disabled, not this.disabled
    }
  });
});

Here's a StackBlitz 显示它正在处理这些更改。