How to pass data between components in Angular using @Input, @Output, and EventEmitter

After selecting a team from an array in one component, I am having trouble passing that selected team to another component. While I can log the selected team in the same component, I'm unable to access it in the other component.

My goal is to use the team's ID to fetch additional details about the team from an API. Any assistance on how to achieve this would be greatly appreciated. Thanks in advance!

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>

Team-detail component

export class TeamDetailComponent implements OnInit {

  @Input() team: any;

  constructor() {
  }

  ngOnInit() {
  }

}

team-detail template(this template only for demo purpose.)

<p>
  {{team.name}}
  {{team.crestUrl}}
  {{team.address}}
  {{team.website}}
</p>

Answer №1

When it comes to the "Output", it refers to the events a component can trigger to send data upwards in the hierarchy to its parent component. In this scenario, if you need to transfer information from the parent component to the child component, you may not require using the Output method.

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>

team-details template

<p *ngIf="team">
  {{team.name}}
  {{team.crestUrl}}
  {{team.address}}
  {{team.website}}
</p>

Answer №2

Implement a property with getter and setter in your child component, while keeping the rest of the code unchanged

_team: any;
get team(): any {
    return this._team;
}

@Input()
set team(value: any) {
    this._team = value;
}

Inside the child component:

<p *ngIf="team">
  {{team.name}}
  {{team.crestUrl}}
  {{team.address}}
  {{team.website}}
</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving data for a route resolver involves sending HTTP requests, where the outcome of the second request is contingent upon the response from the first request

In my routing module, I have a resolver implemented like this: { path: 'path1', component: FirstComponent, resolve: { allOrders: DataResolver } } Within the resolve function of DataResolver, the following logic exists: re ...

Ensure the footer remains at the bottom of the page even with changing

I am encountering an issue with positioning a footer under dynamic content displayed in a div named txtresults. The div is updated with HTML following a query made with an input value, as shown in this example on JsFiddle: JsFiddle Currently, I am struggl ...

Enhancing Plotly Graphs with Custom Node Values

Encountering an issue while attempting to assign values to nodes on a plotly graph. Code: <html> <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <style> .graph-container { ...

The jQuery functions properly offline, but fails to load when connected to the

I am encountering an issue with the following script: <script type="text/javascript"> $.getJSON("http://api.twitter.com/1/statuses/user_timeline/koawatea.json?count=1&include_rts=1&callback=?", function(data) { $("#headertweet") ...

floating point for a list item compared to other elements

nav > ul > li { float: left; } #one { float: left; } <nav> <ul> <li> he has a cow </li> <li > he has a dog </li> <li> he has a mouse </li> </ul> & ...

Angular not utilizing prerendering

I've been struggling for a while now to implement Prerender.io in an Angular 6 project sample without any luck. Although I have managed to serve the application via Express, the page still fails to prerender. Below are the key files (and so far I ca ...

Illustration: Fixing a CSS Issue

After implementing Technique #8 from the Nine Techniques for CSS Image Replacement, I am not getting the desired results. Instead of correctly positioned images, the output is not what I anticipated. Here is a link to see for yourself: I made a modificati ...

Transform the input value into a string

Struggling with converting an input value into a string. HTML: <input type="text" placeholder="Email Ex: john123" id="emailinput"> <input type="text" placeholder="Domain Ex: @gmail.com" id="domaininput"> JS: let emailVal = document.getElem ...

A guide to programmatically downloading a file with JavaScript on Internet Explorer

I'm currently facing a challenge with my web page. There is a button that, when clicked, should generate a CSV file (by converting from JSON) for the user to download. I've implemented the logic based on this jsfiddle, and it works perfectly in C ...

Tips for aligning two objects side by side in HTML

Apologies for the basic question, forgive my ignorance but I am struggling with keeping two objects in the same line within the same division. Please take a look at the code below: <html> <head> <style> .search-input { width: ...

What could be causing my Material UI Table to disappear when I toggle the "Show" option?

I am incorporating the Grow material ui component to display or hide a table. Initially, the table is visible. https://i.sstatic.net/0OxPQ.png <Box className={classes.object_controls_wrapper}> <Box sx={{ display: "flex" }}> ...

The blur() function does not function properly on IOS devices such as iPad and iPhone

I've attempted using blur() to change the CSS, but it seems that this function is not effective. After researching, I discovered that blur() does not work on IOS devices. Is there an alternative method for removing the position from .body-clip-overflo ...

Tips on ending an interval in rxjs once it has started

Implemented a code in an Angular component to retrieve data from a service every 10 seconds on initialization. Now, I need to find a way to stop the interval after a certain period of time such as 5 minutes or when all the necessary data has been collected ...

Personalize the hover effect and underline style of links in material-ui

I am currently delving into the world of material-ui custom styles and came across this helpful resource. However, I find myself a bit lost in how to properly override the classes using withStyles. <Breadcrumbs aria-label="breadcrumb" separator=" ...

When using RxJS forkjoin, it will cease subscription if there is a flatMap present within one of the observables it is awaiting

I have been experimenting with nested calls using rxjs and trying to implement nested forkJoins. However, I have encountered an issue where the outer forkJoin stops returning a result when there is a flatMap inside the inner observable. Here is a snippet ...

Align an image in the middle with a heading

I am currently working on aligning a picture and heading in a header section. My goal is to center both elements, with the picture being twice as tall as the heading. So far, I have them stacked one above the other: .body { font: 15px/1.5 Arial, Helveti ...

Learn how to activate a JS native event listener using jQuery for the 'change' event

This question is unique from the one found at How to trigger jQuery change event in code. The focus here is on the interaction of jQuery with native event listeners, rather than jQuery event listeners. I am using addEventListener to bind a change event fo ...

How come my gifs appear tiny even though I've adjusted their width to 32% each?

I am trying to display three gifs in a row, each taking up one-third of the width of the page. However, when I preview the page, the gifs appear tiny. I have set the divs to 32% each and the gifs should fill 100% of their respective div. Here is the code s ...

Leveraging Express for delegating requests to an ADFS server

We are currently facing a challenge with authenticating to our on-premise ADFS 3.0 server. Our Angular application, a single-page app, needs to authenticate with the ADFS server. However, we are encountering CORS issues due to them not being on the same se ...

Is it possible to pass a parameter to an NGXS action that is not the Payload?

I am working on implementing an Ngxs action that includes a parameter in addition to the payload. This parameter is used to determine whether or not a notification should be sent. @Action(UpdateUser) async UpdateUser( ctx: StateContext<ProfileStat ...