Reusing a row component

November 29, 2023 · 2 min readLucian Ciobanu
Tags:AngularPrimeNG

A cool thing I really like about Angular is that you can reuse the components you have created. So when I noticed we had in our projects rows repeating, I came up with this "row" component:

row.component.html

<div class="grid">
  <div class="col-12 sm:col-6 md:col-4 lg:col-2" i18n>
    <ng-container *ngIf="label; else labelContent">
      <span class="label-container">{{ label }}</span>
    </ng-container>
    <ng-template #labelContent>
      <ng-content select="[label]"></ng-content>
    </ng-template>
  </div>
  <div class="col-12 sm:col-6 md:col-8 lg:col-10">
    <ng-container *ngIf="value; else valueContent">{{ value }}<//ng-container>
    <ng-template #valueContent>
      <ng-content select="[value]"></ng-content>
    </ng-template>
  </div>
  <p-divider class="col-12 mb-2 p-0" *ngIf="displayDivider"></p-divider>
</div>

The classes and directives work with the design I had to implement,PrimeNg library and angular's internationalization.

row.component.ts

import { Component, Input } from '@angular/core'
import { NgIf } from '@angular/common';
import { DividerModule } from 'primeng/divider';

@Component({
  selector: 'app-row',
  templateUrl: './row.component.html',
  styleUrls: ['./row.component.scss'],
  standalone: true,
  imports: [DividerModule, NgIf]
}
           
export class RowComponent {
  @Input() label: string | undefined;
  @Input() value: string | undefined;
  @Input() set isLastItem(isLastItem: boolean) {
    this.displayDivider = !isLastItem;
  }
  displayDivider: boolean = true;
}

I am using standalone components and angula 14 for this project so I need to import NgIf also or I can just import the whole of Angular's common module.

What I really liked about this implementation is that having those ng-content tags in the html gives the developer a lot of flexibility to add more complex things should the desing require it. When you would need something like an icon or more complex, you could do something like this in the parent component:

<app-row label="Something" i18n-label>
  <span value>
    <i class="pi-cirecle fill mr-2" [ngClass="'status-color' + get(Status)"></i>
  </span>
</app-row>

<app-row label="Something Else" i18n-[value]="data.property"></app-row>

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery