我有一個儀表板,其中有登錄用戶組的列表。現在當用戶點擊任何一個組時,該組的基本信息如名稱,描述等將打印在頁面的右側。這是類似的。 如何將變量從一個組件傳遞到另一個組件並在第二個組件模板html文件中打印該變量?
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>
感謝您的@inputs(雙關打算)太.. ..! – shahakshay94