I am having 2 sibling components displayed at the same time to the user. One of them is a QuestionList which takes an array of questions from service and display list of questions. Once you click on a particular question it displays (next to the list) question details like seen below
问题详细信息组件使用路由器从 URL 中获取问题 ID 并将其存储在名为 selectedQuestion 的单独变量中,如下所示:
selectedQuestion: Question;
ngOnInit() {
this.subscription = this.route.params.subscribe(
(params: any) => {
this.questionIndex = params['questionId'];
this.selectedQuestion = this.qs.getQuestion(this.questionIndex);
}
);
}
在模板中,选择的问题使用 [(ngModel)] -> 2 路数据绑定进行绑定,因此我可以通过简单地将所选问题发送到服务来更新问题。
当我在问题详细信息视图中更改某些内容时,我很难理解 Angular2 为何以及如何更新列表?我想因为我创建了名为 selectedQuestion 的单独变量,所以在我将更改推送到使用该服务之前不应更新左侧列表?我对使用 ngModel 的理解是它应该仅以两种方式绑定到 selectedQuestion 并且绝对不会更新我的服务
您引用的是所选问题的相同实例,您需要进行如下修改
导入 lodash,如果你没有安装使用
npm install --save lodash
import * as _ from "lodash";
selectedQuestion: Question;
ngOnInit() {
this.subscription = this.route.params.subscribe(
(params: any) => {
this.questionIndex = params['questionId'];
this.selectedQuestion = _.clone(this.qs.getQuestion(this.questionIndex));
}
);
}
或者,
selectedQuestion: Question;
ngOnInit() {
this.subscription = this.route.params.subscribe(
(params: any) => {
this.questionIndex = params['questionId'];
let jsonQuestionasString JSON.stringify(this.qs.getQuestion(this.questionIndex);
this.selectedQuestion = JSON.parse(jsonQuestionasString);
});
}
有几种替代方案。上面显示了其中一些
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)