Search code examples
angularangular2-templateangular2-services

Angular 2 sibling components 2 way binding


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


Solution

  • 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