Home > Enterprise >  How to handle dynamic pricing plan table in angular?
How to handle dynamic pricing plan table in angular?

Time:02-04

I have an app where there are four types of plans a user can buy. These plans come from the backend and after selecting a plan, the user is navigated to a page where payment is handled. This pricing table page can be viewed again but if the user has bought any plan, the button text will be changed to cancel subscription. Now I can change button text dynamically for all the other plans but if the user cancels a subscription, I do not know how to handle this dynamic button text logic.

There is a stackblitz linked but since the data is coming from the backend I cannot properly demonstrate the functionality. stackblitz

I just need a way to change button text back to 'Choose Plan' after the user cancels a plan.

CodePudding user response:

For the HTML you can do this:

<div >
  <div >
    <button
      type="button"
      *ngIf="planIndex === i"
      (click)="cancelSubscription(plan)">
      Cancel Subscription
    </button> 
    <button
      type="button"
      *ngIf="planIndex !== i"
      (click)="selectSubscription(plan)">

      <span *ngIf="planIndex > i"> Upgrade </span>
      <span *ngIf="planIndex < i"> Downgrade </span>
      <span *ngIf="!planIndex"> Choose plan </span>
    </button>
  </div>
</div>

When you receive your subscriptions from the backend you have to do this

 this.planIndex = this.allSubscriptions.findIndex((sub) => sub.isSubscribed);

You can delete the setDynamicButtonText function

Explanation:

  • if planIndex is null, all buttons are the same "Choose Plan"
  • If we get the index of the subscribed plan, the element with the similar index has "Cancel subscrption" whatever is higher has "Downgrade" whatever is lower is to "Upgrade"

Advice:

  • Never call a function to render HTML in the template it will be called infinitely and it will create bugs. Explanation
  •  Tags:  
  • Related