最后,我找到了解决我的问题的方法。我更新的代码如下:
<ng-template let-i="index" let-c="count" ngFor let-question [ngForOf]="QuestionModel_ddl">
<div class="row">
<div class="col-md-2">
<label for="SecurityQuestion">Security Question {{i+1}} :</label>
</div>
<div class="col-md-6">
<select class="form-control custom-select col-12" (change)="UpdateModelDtls($event, i)" required>
<option value=""></option>
<option *ngFor="let myQuest of QuestionModel_ddl;" [value]="myQuest.QuestionID"> {{myQuest.SecurityQuestion}} </option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-2">
<label for="SecurityQuestion">Security Answer :</label>
</div>
<div class="col-md-6">
<input type="text" [(ngModel)]="QuestionModel_ddl[i]['SecurityAns']" required (focusout)="UpdateSeqAnswer($event, i)" [ngModelOptions]="{standalone: true}" />
</div>
</div>
</ng-template>
我添加了两个方法 UpdateModelDtls 和 UpdateSeqAnswer。在 Component 中,将其定义为
UpdateModelDtls($event: any, i: any) {
debugger;
var item = this.selectedDtls.find(x => x.Index == i);
/* Check if item already present in selectedDtls array. If present, show msg as 'This question is already selected, please select a different question.' */
var IsPresent = this.selectedDtls.find(x => x.QID == this.QuestionModel_ddl[($event.target.selectedIndex - 1)]['QuestionID'] && x.Index != i);
/* In case all the questions dropdowns are selected */
if (item) {
/* Remove the changed dropdown from selectedDtls array since we are making it as not-selected */
var index = this.selectedDtls.indexOf(item);
if (index > -1) {
this.selectedDtls.splice(index, 1);
}
}
if (IsPresent) {
this.IsDuplicateQuestion = true;
$event.target.selectedIndex = -1;
}
else {
this.IsDuplicateQuestion = false;
let item = {
QID: this.QuestionModel_ddl[($event.target.selectedIndex - 1)]['QuestionID'],
Index: i,
SeqAns: this.QuestionModel_ddl[i]['SecurityAns']
};
this.selectedDtls.push(item);
}
}
UpdateSeqAnswer($event: any, i: any) {
debugger;
var item = this.selectedDtls.find(x => x.Index == i);
if (item)
item.SeqAns = $event.target.value;
}
export class SelectedDtls {
QID: string;
Index: number;
SeqAns: string;
}
这两种方法有助于使用所选值更新临时数组 (SelectedDtls)。