Search code examples
angularinputangular7ionic4ngfor

Pass dynamic data from parent to child component in Angular 7


I am having this code:

<ion-item *ngFor="let product of products">
            <ion-label>
              {{ product }}
            </ion-label>
</ion-item>
<ng-container *ngSwitchCase="states.Product">
      <product-details></product-details>
</ng-container>

I want to pass to the product-details child component the value of product from the *ngFor of the parent component. Should I use Input or service? please give example.


Solution

  • Based on your code, you want to access the variable 'product' outside the scope of *ngFor. I can't recommend this behavior but since you have an event-handler within the scope, one way to achieve it is to send the value in the event handler:

    <ng-container *ngFor="let product of products">
      <ion-item>
        <ion-label (mouseup)="mouseUp(product)">
          {{ product }}
        </ion-label>
        <ng-container *ngSwitchCase="states.Product">
          <product-details [productName]='product'></product-details>
        </ng-container>
      </ion-item>
    </ng-container>