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