Search code examples
angulartypescriptionic-frameworkionic5

100% component based Angular/Ionic app development


I have 2 child components as shown below.

Child component 1:

enter image description here

Child component 2:

enter image description here

You can see that its styles, position, and etc are the same. But the content is different. i.e. image and text. So I would like to develop a 100% component based Ionic/Angular app. My question here is do I need to use 2 components here or use the same component with *ngIf with @Input() bindings to determine the different text and image according to the parent page?

e.g. Is this fine or do I need to have 2 complete components for these kinds of use cases? Here it seems tightly coupled with a parent. i.e. changing something will require a lot of work due to the breaking of other places and etc. Am I wrong here?

<ion-grid>
  <ion-row>
    <ion-col size="12" class="ion-text-center padding-bottom-0">
      <h5 class="font-bold margin-top-bottom-5">{{'Client.Parcel-Delivery-Cost' | translate}}</h5>
    </ion-col>

    <ion-col size="12" class="padding-top-bottom-0 ion-text-center" *ngIf="isPickUp">
      <div>{{'Client.Parcel-Picked-Up-From-The-Location-And-Delivered-To-You' | translate}}</div>
    </ion-col>

    <ion-col size="12" class="padding-top-bottom-0 ion-text-center" *ngIf="!isPickUp">
      <div>{{'Client.Parcel-Picked-Up-And-Handed-Over-To-Respective-Courier' | translate}}</div>
    </ion-col>

    <ion-col size="12" class="padding-top-bottom-0 ion-text-center font-bold">
      <h4 class="margin-top-5 font-bold"> {{parcelDeliveryCost}}</h4>
    </ion-col>
  </ion-row>
</ion-grid>

Solution

  • In this particular case, you just need one component, a dumb Component. Lets name it StepComponent

    export class StepComponent implements OnInit {
    @Input() details: DetailData;
    
    constructor(){}
    ngOnInit(){}
    
    }
    

    Then in the template, you should access the details property and render the data. The DetailData type is just a model to hold all the details properties (e.g name, description, image).

    <h4>{{details.name}}</h4>
    <p{{details.description}}</p>
    

    There's also a different technique that can be useful to reuse some logic but render something different if required. It is called content projection and it's nicely explained here: https://www.prestonlamb.com/blog/content-projection-in-angular