Angular 2 sibling components 2 way binding

那年仲夏 提交于 2019-12-10 18:13:05

问题


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

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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/42317036/angular-2-sibling-components-2-way-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!