简体   繁体   English

在组件或路径之间传递数据,angular4

[英]passing data between components or route, angular4

I have a list of cards, each card has some data like {"phone":"333-123-4566", "cust_name":"john smith"} 我有一张卡片清单,每张卡片都有一些数据,例如{"phone":"333-123-4566", "cust_name":"john smith"}

I have a list component and a card component to display the phone and name. 我有一个列表组件和一个卡组件来显示电话和姓名。

How does angular2 or angular4 pass the item data into card component? angular2或angular4如何将商品数据传递到卡片组件中? I need to know which card is clicked and display the right phone/name. 我需要知道单击了哪个卡并显示正确的电话/名称。

In Angular 1, it was very simple with ngModel, but I am not finding a simple solution in angular2/4. 在Angular 1中,使用ngModel非常简单,但是我没有在angular2 / 4中找到简单的解决方案。

<ul>
  <li *ngFor="let item of items; let i=index;">
    <a routerLink="/card" > {{item.cust_name}} </a>
  </li>
</ul> 

The two most common choices are: 两种最常见的选择是:

1) Pass the information as part of the route. 1)将信息作为路线的一部分传递。 You can do this three ways: required, optional, or query parameters. 您可以通过三种方式执行此操作:必需,可选或查询参数。

I have details on this here: Sending data with route.navigate in Angular 2 我在这里有详细信息: 在Angular 2中使用route.navigate发送数据

2) Define a service that holds the data and access that service from both components. 2)定义一个保存数据的服务,并从两个组件访问该服务。

I have an example of this here: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/ 我在这里有一个示例: https : //blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

 <ul>
      <li *ngFor="let item of items; let i=index;">
        <a routerLink="['/card', {"phone":"333-123-4566", "cust_name":"john smith"}]"> {{item.cust_name}} </a>
      </li>
    </ul>     

<ul>
      <li *ngFor="let item of items; let i=index;">
        <a (click)=navigate(item)> {{item.cust_name}} </a>
      </li>
    </ul> 


navigate(item) : void {  
  this.router.navigate(['/card', {"phone":"333-123-4566", "cust_name":"john smith"}])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM