Angular 2 sibling components 2 way binding

2019-07-03 19:11发布

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 enter image description here

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);
      }
      );
  }

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.

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

2条回答
叼着烟拽天下
2楼-- · 2019-07-03 19:18

It looks like you are sharing the same instance of question between two components, during change detection both components detect changes and they both get updated.

查看更多
不美不萌又怎样
3楼-- · 2019-07-03 19:23

You are refering to same instances of the selected question and you need to modify as below

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));
      }
      );
  }

Alternatively,

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

查看更多
登录 后发表回答