Search code examples
angularangular2-components

call component two from component one and pass data from component one


I have two components component1(showing a list of items), component2(showing item details), component2 is hidden by default. i want : when a user click on a list item in component2, the component2 should show the details for the selected item. For this i created a shared service, the service shares data and works fine my problem is: 1: how do I make component2 aware of click events on component1, so that it loads the details for clicked item after user clicked an item on list view. 2: component 2 is hidden using *ngIf="isComponent2Visible", how can i show it after a user click on an item in component1(listview). I hope the question is easy to understand and good structured.


Solution

  • You can do this easily using *ngIf as you did. Just call a function when item is clicked and pass its item Id like (click)="display(item.id)" set this Id to component property so that you can access it in your template.

    Component

    displayItemId: number = 0;
    
    display(id:number){
       this.displayItemId = id;
    }
    

    HTML

    <display-component *ngIf="displayItemId>0" [displayItemId]="displayItemId"></display-component>
    

    And in your display component use this @Input() displayItemId to get specific details in ngOnInit() function.

    OR If you want to use the current item or already fetched details in your first component then pass whole item as input and use it on second component's template.

    Component

    displayItem: any;
    
    display(item:any){
       this.displayItem = item;
    }
    

    HTML

    <display-component *ngIf="displayItem" [displayItem]="displayItem">
    

    Other (recommended) approach is to use router. Just navigate to a URL containing Id items/details/5, get Id from route in your second component and use it to fetch details.