繁体   English   中英

如何在Angular中将对象从一个组件传递到另一个组件

[英]How to pass an object from one Component to another in Angular

我正在使用angular2版本。 我有一个网格,其中有编辑按钮。 每当我单击编辑时,我都需要实现,它应该显示其他组件,并且该对象应该传递给该组件。 我的看法如下:

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

现在如何将用户对象传递给其他名为edituser.component.ts的组件。 请提出建议。

代替这个:

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

您只需要将一个功能绑定到该'a'标记,并像这样在该功能中进行所有导航和其他用户选择即可;

在users.component.html中:

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

在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]);
   }`

有关更多信息,我建议您查看官方的《角力英雄》教程: https : //angular.io/docs/ts/latest/tutorial/toh-pt6.html

设置一个非常基本的服务来保存数据? :-

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

}

然后编辑html,以便单击以设置用户(click)=setUserSelected(user)

暂无
暂无

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

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