我正在尝试将一组团队中的一个团队传递给另一个组件,并使用它。我在与console.log相同的组件(团队)中选择了团队,但没有在另一个组件(团队详细信息)中加入
实际上,我想使用团队ID从API中获取有关团队的其他详细信息。请帮助我解决这个TIA
Team.component.ts
export class TeamsComponent implements OnInit {
@Output() selectedTeam = new EventEmitter<any>();
constructor(private general: GeneralService) {
}
teamsObject: any;
teams: [];
ngOnInit() {
this.loadTeams();
}
loadTeams() {
this.general.getTeams().subscribe(data => {
this.teamsObject = data;
this.teams = this.teamsObject.teams;
});
}
onSelectTeam(team: any) {
this.selectedTeam.emit(team);
}
}
Team.component.html
<div class="container-fluid " >
<div class="row " >
<div class="col-xs-12" *ngFor="let team of teams">
<div class="card border-dark " style="width: 250px; height: 450px; margin: 10px;" (click)="onSelectTeam(team)">
<img class="card-img-top embed-responsive" src="{{team.crestUrl}}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{team.name}}</h5>
<p class="card-text">{{team.address}}</p>
<a href="{{team.website}}" class="btn btn-primary" target="_blank">Visit Website</a>
</div>
</div>
</div>
</div>
<app-team-detail *ngIf="selectedTeam" [team]="selectedTeam"></app-team-detail>
</div>
团队细节组件
export class TeamDetailComponent implements OnInit {
@Input() team: any;
constructor() {
}
ngOnInit() {
}
}
team-detail模板(此模板仅用于演示。)
<p>
{{team.name}}
{{team.crestUrl}}
{{team.address}}
{{team.website}}
</p>
答案 0 :(得分:2)
“输出”标识组件可以触发以将层次结构中的信息发送到其父级的事件。在这种情况下,您希望将信息从父组件发送到子组件。因此,您无需使用Output。
Team.component.ts
export class TeamsComponent implements OnInit {
selectedTeam:any;
constructor(private general: GeneralService) {
}
teamsObject: any;
teams: [];
ngOnInit() {
this.loadTeams();
}
loadTeams() {
this.general.getTeams().subscribe(data => {
this.teamsObject = data;
this.teams = this.teamsObject.teams;
});
}
onSelectTeam(team: any) {
this.selectedTeam = team;
}
}
team.component.html
<app-team-detail *ngIf="selectedTeam" [team]="selectedTeam"></app-team-detail>
团队详细信息模板
<p *ngIf="team">
{{team.name}}
{{team.crestUrl}}
{{team.address}}
{{team.website}}
</p>
答案 1 :(得分:1)
在子组件中使用getter和setter创建属性,其余代码保持不变
_team: any;
get team(): any {
return this._team;
}
@Input()
set team(value: any) {
this._team = value;
}
在儿童中
<p *ngIf="team">
{{team.name}}
{{team.crestUrl}}
{{team.address}}
{{team.website}}
</p>