2016-03-28 98 views
0

我使用角2.0.0-beta.9(變化)事件不觸發動態創建的複選框

我有使用動態創建一些複選框輸入對象的打字稿數組:

<span *ngFor="#rank of rankList" style="display:inline-block;"> 
    <input type="checkbox" id="{{rank.Code}}" (change)="onRankChange(object.selected)"> 
    <label [attr.for]="rank.Code">{{rank.Title}}</label> 
</span> 

然後在我打字稿類的組件的我定義onRankChange方法:

export class EditComponent implements OnInit { 

    selectedRanks: Rank[]; 

    constructor(fBuilder: FormBuilder) { 

      // build form controls 
     this.shiftForm = fBuilder.group({ 
      'OwnerEmail': ['', Validators.compose([ 
       Validators.required, this._shiftValidator.validateEmail 
      ])], 
      'TradeDate': ['2016-03-23', Validators.required], 
      'OwnerUserID': [0, Validators.compose([ 
       Validators.required, this._shiftValidator.validateSelect 
      ])], 
      'PlatoonID': [0, Validators.compose([ 
       Validators.required, this._shiftValidator.validateSelect 
      ])], 
      'BranchID': [0, Validators.compose([ 
       Validators.required, this._shiftValidator.validateSelect 
      ])], 
      'StatusID': [0, Validators.compose([ 
       Validators.required, this._shiftValidator.validateSelect 
      ])] 
     }); 
    } 

    onRankChange(cbID: string, selected: boolean): void { 
     // get the rank object that matches the supplied id 
     let cRank: Rank = this.rankList.filter((r: Rank) => r.Code === cbID)[0]; 

     // if no rank found exit function 
     if (cRank === null) { 
      return null; 
     } 

     // check to see if object exists in the selectedRank array already 
     let found: Boolean = this.selectedRanks.some((r: Rank) => { return r.Code === cbID; }); 

     if (selected === true && !found) { // add rank to selectedRank Array 
      this.selectedRanks.push(cRank); 
     } 

     if (selected === false && found) { // remove rank id from string list 
      // get index of element 
      let idx: number = this.selectedRanks.indexOf(cRank); 
      // splice array to remove element arguments (index, numberOfElementsToRemove) 
      this.selectedRanks = this.selectedRanks.splice(idx, 1); 
     } 
    } 
} 

的複選框未被添加到形式的控制組。這就是爲什麼他們不排放事件?如果是這樣,我將如何動態創建控件並將其添加到控件組中?

回答

0

添加以下到我的組件的我的ngOnInit方法:

ngOnInit(): void { 

    // add rank checkboxes to formbuilder's control group 
    this.rankList.forEach((r: Rank) => this.shiftForm.addControl(r.Code, new Control(''))); 

}