DEV Community

Ricardo Torres
Ricardo Torres

Posted on • Originally published at ricardo-torres.me on

Components - Gallery of Fruits

@Input to send messages from Parent to Child

@Output to send messages from Child to Parent

Understand the concept of Communication between components is basic to develop any Application in angular.

We must render a list of fruits by using 2 components:

1- product-list

<div class="container" id="navbar-container">
  <section class="section">
    <div class="container">
      <div class="has-text-centered" id="services-text-container">
        <h1 class="title is-1">Gallery of Fruits</h1>
      </div>
      <br />
      <div class="columns">
        <app-product-card
          *ngFor="let item of record"
          [product]="item"
        ></app-product-card>
      </div>
    </div>
  </section>
</div>
Enter fullscreen mode Exit fullscreen mode

In the component product-list, we must call the service productService to get the data.

import { Component, OnInit } from '@angular/core';
import { Record } from 'src/app/model/record';
import { ProductService } from 'src/app/services/product.service';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.scss'],
})
export class ProductListComponent implements OnInit {
  record: Record[] = [];
  constructor(private productService: ProductService) {}

  ngOnInit(): void {
    this.getProducts();
  }

  getProducts(): void {
    this.productService.getProducts().subscribe((data) => {
      this.record = data.record;
    });
  }
}

Enter fullscreen mode Exit fullscreen mode

2-product-card

<div class="column">
  <div class="card">
    <div class="card-content">
      <div class="has-text-centered">
        <img [src]="product.image" />
      </div>
      <h3 class="title is-3 has-text-centered" id="card-product-description">
        {{ product.name }}
      </h3>
      <p class="has-text-centered">
        {{ product.description }}
      </p>
    </div>
  </div>
</div>

Enter fullscreen mode Exit fullscreen mode

In the Typescript we must to define an @Input property named product, it is going to receive the data from the parent component (product-list).

import { Component, Input, OnInit } from '@angular/core';
import { Record } from 'src/app/model/record';

@Component({
  selector: 'app-product-card',
  templateUrl: './product-card.component.html',
  styleUrls: ['./product-card.component.scss'],
})
export class ProductCardComponent implements OnInit {
  @Input() product!: Record;
  constructor() {}

  ngOnInit(): void {}
}

Enter fullscreen mode Exit fullscreen mode

Live Demo

Download Code

Top comments (0)