Kathrine Hanson
Kathrine Hanson

Reputation: 625

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.

Upvotes: 0

Views: 4583

Answers (3)

Barremian
Barremian

Reputation: 31125

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>

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86740

Simply use @Input decorator for data passing from parent to child component. For dynamic binding, you can use attribute binding [] like below -

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

@Input('productName') productName: type

Also, keep in mind you can get the value passed in the ngOnInit life cycle hook, not in the constructor of the child component.

Refer to the working example below for your reference.

Working Example

Upvotes: 3

Blind Despair
Blind Despair

Reputation: 3295

Your product details are not inside *ngFor, you can only pass product to <product-details> if it is inside the scope of it. I of course recommend using input here, because it helps keeping your product-details component independent and have a role of presentation only component. If you used a service, it would rely on the fact that the service has to get data from somewhere, which would make product-details too complex in this case. Here is example:

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

And in your product-details.component.ts:

@Input() product: Product;

Upvotes: 1

Related Questions