在另一个组件中显示选定的列表项值 [英] To display selected list-item values in another component

查看:32
本文介绍了在另一个组件中显示选定的列表项值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个组件,称为 list(i,e Person list) 和 details(i,e Person details),我显示如下:

I have 2 components called list(i,e Person list) and details(i,e Person details) which i am displaying like this:

这里我的要求是:在为 ex:Person 1 选择特定的 list-item 时,我想显示 Person 1 的详细信息details 组件出现在右侧,如下所示:

Here my requirements is: On selecting particular list-item for ex:Person 1, I want to display the Person 1 details on details component which present on the right side, something like this:

如何为 list 组件中的单个 list-item(即 Person 1、Person 2 ....)分配值并将它们传递给 details 组件显示在第二张图片中.我看到了一些示例,但它们不符合我的要求.

How can i assign values for individual list-item (i,e Person 1, Person 2 ....) in list component and pass them to details component to display as shown in 2nd image.I saw some examples but they are not matching to my requirement.

演示

推荐答案

有几种方法可以在不同的组件之间进行通信.在您的情况下,您可以使用服务进行通信.

There are several way to communicate among different components. In your case you can use Services to communicate.

工作演示在这里 - https://stackblitz.com/edit/list-examples-nh4hik

这是将一个组件与另一个组件进行通信的服务.

This is the service which will communicate between one component to another.

import { Injectable } from '@angular/core';
import { Subject , Observable} from 'rxjs';

@Injectable()
export class PersonService {

  person$ = new Subject();

  public setPerson(person){
    this.person$.next(person);
  }

  public getPerson() : Observable<any>{
    return this.person$.asObservable();
  }

}

列表组件

export class ListComponent {

  constructor(private personService : PersonService){}

  public setSelected(person){
    this.personService.setPerson(person);
  }

}

详细信息组件

export class DetailsComponent implements OnInit {

  person : any;
  constructor(private personService : PersonService){}

  ngOnInit() {

    this.personService.getPerson().subscribe(person=>{ //<-- subscribe 

      this.person = person;
    });

  }

}

这篇关于在另一个组件中显示选定的列表项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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