简体   繁体   中英

How to pass an object from one Component to another in Angular

I am working on angular2 version. I have a grid in which i have edit button. I need to implement whenever i click on edit it should display other component and that object should be passed to that component. My view is as below:

  <table class="table table-striped" width="50%">
  <tr> 
     <td>User Name</td>
     <td>Email</td>
     <td>Gender</td>     
     <td></td>
  </tr>
  <tr *ngFor="let user of Users">
     <td>{{user.UserName}}</td>
     <td>{{user.Email}}</td>
     <td>{{user.Gender | transformgender }}</td>
     <td><a  routerLink="/edituser" routerLinkActive="active">Edit</a></td>  
  </tr>
</table>
<a class="btn btn-primary" routerLink="/adduser" routerLinkActive="active">Add User</a>

Now how can a pass user object to other component called edituser.component.ts. Please suggest.

Instead of this:

<td><a  routerLink="/edituser" routerLinkActive="active">Edit</a></td> 

You need to just bind a funcion to that 'a' tag and do all the navigation and other user selection in that function like this;

in the users.component.html:

<td><a  (click)="editThisUser()" routerLinkActive="active">Edit</a></td>

in the users.component.ts:

`

// add Router to the top of the component
   import { Router } from '@angular/router';
 //...... some other codes....//
 //in the component class 
   constructor(private router: Router) {}
 //and define the function that you bind in the users.component.html
   editThisUser(): void {
     this.router.navigate(['/edituser', this.selectedUser.id]);
   }`

for further information i suggest you to check the official angular heroes tutorial: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

Setup a very basic service that hold data? :-

import { Injectable } from '@angular/core';
import { Component, OnInit } from '@angular/core';

@Injectable()
export class UserSelectedService {
    public userSelected: any = {}; 
}


@Component({
    selector: 'user-view',
    templateUrl: 'user-view.html',
    styleUrls: ['user-view.scss']
})

export class UserViewComponent implements OnInit {

    public user: any;

    constructor(private _userSelectedService: UserSelectedService) {}

    public ngOnInit() {
        this.user = this._userSelectedService.userSelected;
    }

}

Then edit html so that when clicked to set the user (click)=setUserSelected(user) .

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