2017-02-20 37 views
1

我想根據它的ID「檢查」複選框。如何選擇ID爲Angular2的複選框

模板HTML:

div class="panel panel-default" *ngFor="let optionsList of option.options"> 
      <div class="panel-heading panel-heading-divider"><input type="checkbox" id="{{optionsList.id}}" value="{{optionsList.id}}">{{optionsList.id}}</div> 
      <div class="panel-body">{{optionsList.description}}</div> 
     </div> 

控制器組件:

foo(selected: number): void { 
    this._service.foo(bar, options, selected).subscribe(
     res => { 
     this.validation = res; 
     if(this.validation.furtherAdditions.length > 0) { 
      this.validation.furtherAdditions.forEach(
      option => 
      //'checked' checkbox by id from validation 
     ); 

     } 
     }, 
      error => this.errorMessage = <any>error 
    ); 

換句話說,我有一堆dynaamically使用ngFor創建複選框輸入。數據是可變的,因爲它是從API填充的。我已經從API響應中記錄了驗證ID(需要「檢查」什麼),並且對於每個ID,我想選擇它。我將如何使用angular2去解決這個問題?

回答

1

考慮這種潛在的選項:

一下添加到輸入複選框:

[selected]="checkIfSelected(optionsList.id)" 
在組件

然後:

public checkIfSelected(currentId){ 
    if(!this.validation) return; 
    return this.validation.furtherAdditions.some(id => id == currentId); 
} 
+1

非常感謝您的幫助! – Moshe