简体   繁体   中英

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"}

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? 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.

<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. 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

2) Define a service that holds the data and access that service from both components.

I have an example of this here: 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"}])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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