簡體   English   中英

如何將變量從一個組件傳遞到另一組件,並在第二個組件模板html文件中打印該變量?

[英]How to pass variable from one component to another component and print that variable in 2nd Component template html file?

我有一個儀表板,其中包含登錄用戶所在的組的列表。 現在,當用戶單擊任何一個組時,該組的基本信息(例如名稱,說明等)就會打印在頁面的右側,就像這樣。 在此處輸入圖片說明

HomeComponent有一個名為GroupComponent子組件。 我試圖將組對象從HomeComponent傳遞到GroupComponent,該組件將打印其名稱。 以下是我嘗試過的代碼:

routes.ts

export const routes: Routes = [
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'login', component: LoginComponent},
  {
    path: 'home', component: HomeComponent, canActivate: [AuthGuard],
    children: [
      {path: '', redirectTo: 'dashboard', pathMatch: 'full'},
      {path: 'group', component: GroupComponent},
      {path: 'dashboard', component: DashboardComponent}
    ]
  }
];

home.component.ts

export class HomeComponent implements OnInit {
  user: string;
  user_id: number;
  group_list: string[];

  constructor(public router: Router, private _groupService: GroupService) {
    // xyz code
  }

  ngOnInit() {
  }

  getUserGroups() {
    let body: string = '{}';
    this._groupService.getAllUserGroups(body).subscribe(
      auth => {
        let payload = auth.json();
        this.group_list = payload.list;
      },
      error => {
        console.log(error);
      }
    );
  }

  goToGroupDetail(group) {
    console.log(group.id);
    let groupObj = new GroupComponent(group.name);
    this.router.navigate(['/home/group']);
  }

}

home.component.html

<ul class="nav navbar-nav navbar-right">
            <li *ngFor="let group of group_list"><a  (click)="goToGroupDetail(group);">{{group.name}}</a></li>
          </ul>

group.component.ts

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

@Component({
  selector: 'app-group',
  templateUrl: './group.component.html',
  styleUrls: ['./group.component.css']
})
export class GroupComponent implements OnInit {
  group_name:string;

  getGroupName(): string {
    return this.group_name;
  }

  setGroupName(value){
    this.group_name = value;
  }

  constructor(name:string) {
    this.setGroupName(name);
  }
  ngOnInit() {
  }

}

group.component.html

<p>
  group works!
</p>
<div class="col-md-6">
  <h2>Name of the Group : {{group_name}}</h2>
</div>

我收到這種錯誤: 在此處輸入圖片說明

您有兩個選擇可以使用navparams或@ViewChild。 這確實取決於您的要求。

對於您的情況,我建議您使用簡單的navparams。 這是一個有用的鏈接 如果您仍然找不到解決方案,我會為您提供幫助。

您正在嘗試無法完成的工作...含義如下行: let groupObj = new GroupComponent(group.name); 然后期望能夠獲得在構造函數中注入的值。

在組件之間共享數據的最常見方案是使用共享服務。

Sp與BehaviorSubject一起使用共享服務在路由之前,設置組,然后在GroupComponent訂閱主題。

在您的GroupService ,導入BehaviorSubject並聲明以下內容:

import {BehaviorSubject} from 'rxjs/BehaviorSubject';

private group = new BehaviorSubject<string>(null);

group$ = this.group.asObservable();

emitGroup(group: string) {
  this.group.next(group);
}

並在您的HomeComponent中將組傳遞給Service:

goToGroupDetail(group) {
  console.log(group.id);
  this._groupService.emitGroup(group); // here
  this.router.navigate(['/home/group']);
}

然后在您的GroupComponent您可以在構造函數中訂閱它:

constructor(private _groupService: GroupService) {
  _groupService.group$.subscribe(group => {
     this.group_name = group; // assign value here
  });
}

有關共享服務的更多信息來自官方文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM