Angular 2 兄弟组件 2 路绑定 [英] Angular 2 sibling components 2 way binding
问题描述
我同时向用户显示了 2 个同级组件.其中之一是 QuestionList ,它从服务中获取一系列问题并显示问题列表.单击特定问题后,它会显示(在列表旁边)问题详细信息,如下所示
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 的单独变量中,如下所示:
Question detail component uses router to take question id from the URL and stores it in a separate variable called selectedQuestion like this:
selectedQuestion: Question;
ngOnInit() {
this.subscription = this.route.params.subscribe(
(params: any) => {
this.questionIndex = params['questionId'];
this.selectedQuestion = this.qs.getQuestion(this.questionIndex);
}
);
}
在模板中 selectedQuestion 使用 [(ngModel)] -> 2 路数据绑定进行绑定,因此我可以通过简单地将 selectedQuestion 发送到服务来更新问题.
In the template selectedQuestion is binded using [(ngModel)] -> 2 way data binding so I can update the question by simply sending selectedQuestion to the service.
当我在问题详细信息视图中更改某些内容时,我很难理解 Angular2 为什么以及如何更新列表? 我认为因为我创建了名为 selectedQuestion 的单独变量,左侧的列表不应该是更新直到我推送更改以使用该服务?我对使用 ngModel 的理解是它应该以 2 种方式只绑定到 selectedQuestion 并且绝对不更新我的服务
I am struggling to understand why and how Angular2 updates the list when I change something in the question detail view? I thought cause I have created separate variable called selectedQuestion, list on the left should not be updated till I push changes to using the service? My understanding of using ngModel is that it should 2 way bind to selectedQuestion only and definitely not update my service
推荐答案
您引用了所选问题的相同实例,需要进行如下修改
You are refering to same instances of the selected question and you need to modify as below
导入 lodash,如果你没有使用
Import the lodash, if you dont have install using
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);
});
}
有几种替代方法.上面显示了一些
There are a several alternatives to it. few of which is shown above
这篇关于Angular 2 兄弟组件 2 路绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!