Home > front end >  How to evaluate column values in two *ngFor arrays in angular
How to evaluate column values in two *ngFor arrays in angular

Time:04-26

I am working in an angular app , the goal is to evaluate if a user has a subscription for the listed service (which is an array).

  servicesList = [
    {
      name: "medical",
    },
    {
      name: "security",
    },
    {
      name: "roadside",
    },
  ];

I want to do a comparison with what the user has subscribed on then show a UNLINK button if there is a subscription for that service else show LINK

THe Subscription data is as follows

  subscriptions = [
    {
      service: "medical",
      company_id: "32563
    },
    {
      name: "security",
      company_id: "25801"
    }
  ];

enter image description here

CodePudding user response:

create a find function and use *ngIf

isUserSubscribed(sub: string) {
return this.subscriptions.find(x => x.subscriptions == sub);
}

in HTMl use *ngIf

<button *ngIf="!isUserSubscribed('medical')" >Link</button>
<button *ngIf="isUserSubscribed('medical')" >Unlink</button>

Change the argument according to the option you want to validate.

CodePudding user response:

I'd like to build upon the answer that Vamsi shared. You can create a find function that will let you know if a user is subscribed or not and then you can use that function in your *ngIf.

isUserSubscribed(title: string): boolean {
    return this.subscriptions.findIndex(sub => sub.service === title) > -1;
}

Then, in your HTMl you can use *ngIf as follows:

<button *ngIf="!isUserSubscribed('medical')">Link</button>
<button *ngIf="isUserSubscribed('medical')">Unlink</button>
  • Related