我遇到了离子选择动态数据过滤的奇怪错误。在我的应用程序中,用户应该在注册期间选择三个安全问题,因此这些问题不能相同。我有一系列问题:
questions: Array<{isSelected: boolean;question: string}> = [
{isSelected: false, question: 'What is your pet’s name?'},
{isSelected: false, question: 'What is the first name of the person you first kissed?'},
{isSelected: false, question: 'Who was your childhood hero?'},
{isSelected: false, question: 'What was your first grade friend last name?'},
{isSelected: false, question: 'Where did you celebrate your 20th birthday?'},
{isSelected: false, question: 'In what city or town does your nearest sibling live?'},
{isSelected: false, question: 'What time of the day were you born?'}];
我的注册表格的这一部分如下所示:
<ion-item>
<ion-label floating>Select security question*</ion-label>
<ion-select [(ngModel)]="regModel.SecurityQuestions[i].Question" name="Question"
[selectOptions]="sqSelectOptions"
(ionChange)="chooseQuestion(regModel.SecurityQuestions[i].Question)">
<ion-option *ngFor="let sqOption of questions|filterSQ" value="{{sqOption.question}}"> {{sqOption.question}}
</ion-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label floating>Your answer*</ion-label>
<ion-input type="text" required [(ngModel)]="regModel.SecurityQuestions[i].Answer" name="Answer"></ion-input>
</ion-item>
</div>
我使用(ionChange)="chooseQuestion(regModel.SecurityQuestions[i].Question)
来跟踪所选的选项:
chooseQuestion(s: string) {
console.log(this.TAG + 'chooseQuestion: event value: ' + s);
this.questions.filter(res => res.question == s).map(res => res.isSelected = true);
//todo rewrite this
this.questions.filter(res => res.isSelected == true &&
res.question != this.regModel.SecurityQuestions[0].Question &&
res.question != this.regModel.SecurityQuestions[1].Question &&
res.question != this.regModel.SecurityQuestions[2].Question)
.map(res => res.isSelected = false);
this.questions_filtered = this.questions.filter(res => res.isSelected == false);
console.log(this.TAG + 'chooseQuestion: questions: ' + JSON.stringify(this.questions));
console.log(this.TAG + 'chooseQuestion: questions_filtered: ' + JSON.stringify(this.questions_filtered));
}
根据日志逻辑工作正常。我第一次使用questions_filtered来提供离子选择和遇到问题的问题:选择的选项不会显示在UI字段中。然后我尝试使用管道作为过滤数据的推荐方式,同样影响。 我将不胜感激任何建议。谢谢。
更新
为了澄清这个案例,我添加了一些记录并重写了一点代码。本例中的三个问题中有两个有管道,最后一个没有。我得到正确的值,但没有实际显示。
更新
我仍然不知道为什么 @ misha130 提出的解决方案没有给出任何结果。所以我试着去挖掘Chrome检查器,发现这个部分没有被调用。(我复制了突出显示的部分,但我不确定它是否正确)http://plnkr.co/edit/n4wv2UUdLtCmt4enYuVS?p=catalogue
答案 0 :(得分:1)
Angular2不会检测数组及其子对象的更改。要在视图中实际生效,您必须调用更改检测
import { ChangeDetectorRef } from '@angular/core';
// Inject to constructor
constructor(public cd:ChangeDetectorRef){}
// as per your example call it on in your ionChange method
chooseQuestion(s: string) {
this.cd.detectChanges();
}
有关详细信息:http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html