(更改)事件不会为动态创建的复选框触发

时间:2016-03-28 17:53:58

标签: typescript angular

我使用的是角度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>

然后在我的组件的typescript类中,我定义了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);
        }
    }
}

复选框未添加到表单控件组。这就是为什么他们不发射事件?如果是这样,我将如何动态创建控件并将其添加到控件组?

1 个答案:

答案 0 :(得分:0)

我将以下内容添加到我的组件的ngOnInit方法中:

ngOnInit(): void {

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

}