[英]How to pass an object from one Component to another in Angular
I am working on angular2 version. 我正在使用angular2版本。 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. 现在如何将用户对象传递给其他名为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; 您只需要将一个功能绑定到该'a'标记,并像这样在该功能中进行所有导航和其他用户选择即可;
in the users.component.html: 在users.component.html中:
<td><a (click)="editThisUser()" routerLinkActive="active">Edit</a></td>
in the users.component.ts: 在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 有关更多信息,我建议您查看官方的《角力英雄》教程: 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)
. 然后编辑html,以便单击以设置用户(click)=setUserSelected(user)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.