2017-04-20 93 views
1

我指的是Ionic 2 read checkbox value代碼,與答案中所述的相同。但我在控制檯收到錯誤消息:離子2複選框值

Cannot read property 'indexOf' of undefined 

下面是我的代碼home.html的:

<form #leadsForm = "ngForm"> 
    <ion-item> 
     <ion-label>Assign to: </ion-label> 
     <ion-select [(ngModel)]="saleRep" name="saleRep"> 
      <ion-option *ngFor="let agency of agencyReps;let i = index;" value="{{agencyRepsIds[i]}}"> {{ agencyReps[i] }}</ion-option>       
     </ion-select> 
    </ion-item> 
    <button ion-button (click)="assignLeads()" block>Assign</button> 

    <ion-list > 
     <ion-item *ngFor="let t of leads;"> 
      <h2 [ngClass]="t.status">{{t.fname}} {{t.lname}} | {{ t.status}}</span></h2> 
      <label> 
       <input type="checkbox" value="{{t}}" [checked]="cbChecked.indexOf('t') >= 0" (change)="updateCheckedOptions(t, $event)" /> 
      </label> 
     </ion-item> 
    </ion-list> 
</form> 

引線在* ngFor直接從後臺獲取和引線的數據列出完美的罰款。

home.ts如下:

export class Leads { 
    cbChecked: string[]; 
    saleRep; 

    constructor() { } 

    updateCheckedOptions(chBox, event) { 
     var cbIdx = this.cbChecked.indexOf(chBox); 

     if(event.target.checked) { 
      if(cbIdx < 0){ 
       this.cbChecked.push(chBox); 
      console.log(chBox); 
      } 
     } else { 
      if(cbIdx >= 0){ 
      this.cbChecked.splice(cbIdx,1); 
       console.log(cbIdx); 
      } 
     } 
    } 

    assignLeads(){ 
     console.log('Selected Representative',this.saleRep) 
     console.log('CheckBox Value',this.cbChecked); 
    } 

} 

謝謝。

回答

1

兩點:

  • cbChecked: string[] = [];需要有一個初步的價值!否則它的undefined!
  • [checked]="cbChecked.indexOf(t) >= 0"使用t這裏,而不是't'
+0

謝謝@mxii。這個對我有用。你挽救了我的另一半天。 –

+0

不客氣!祝你好運,快樂編碼.. :) – mxii

1

您尚未初始化任何地方的cbChecked

集:

constructor() { 
    this.cbChecked=[]; 
} 
+0

謝謝@suraj的回覆。 –

+0

沒問題:) ..錯過了't'雖然 –