Angular 2同级组件2方式绑定 [英] Angular 2 sibling components 2 way binding

查看:56
本文介绍了Angular 2同级组件2方式绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我同时向用户显示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的理解是,它应该仅以两种方式绑定到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

如果没有使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆