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

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

问题描述

我有两个组件,分别显示为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时,我想在右侧显示的details组件上显示Person 1详细信息,例如这个:

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

}

DetailsComponent

export class DetailsComponent implements OnInit {

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

  ngOnInit() {

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

      this.person = person;
    });

  }

}

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

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