angularangular8angular-arrays

how to create a hyperlink for values from an array in Angular 8


I have data that looks something like this

plans:[
  {
    "planName": "PlanA",
    "planCode": "PLN001"
  },
  { 
    "planName": "PlanB",
    "planCode": "PLN002"
  },
  {
    "planName": "PlanC",
    "planCode": "PLN003"
  }
]

I need to display in UI HTML like below

<p> User 1 is enrolled in PlanA , PlanB , PLanC </p>

question1: How to get the values from the plans array to display like above with commas in one statement.

question2: I need to give a hyperlink to each plan to the question1 statement which will take to a different component based on the plan code.

<a href="#{planCode}_details">{{PlanName}}</a>

The other components that the hyperlink has to take have an id to it

id="{{p.planCode}}_details"

Any help is appreciated

This is what I tried so far.

<p *ngIf="plans?.length > 0">{{UserName}} has a balance in the {{plans.planName.join(', ')}} .</p>

Solution

  • Question 1

    var plans = [ { "planName": "PlanA", "planCode": "PLN001" }, { "planName": "PlanB", "planCode": "PLN002" }, { "planName": "PlanC", "planCode": "PLN003" }]
    
    var result = (plans.map(plan => plan.planName)).reduce((acc, curr) => acc + ', ' + curr)
    
    console.log(result);
    You could try the following to obtain a comma separated string of all planName properties.

    planNames: string;
    
    this.planNames = (plans.map(plan => plan.planName)).reduce((acc, curr) => acc + ', ' + curr);
    

    And use it the template

    <p> User 1 is enrolled in {{ planNames }} </p>
    

    Question 2

    You could bind member variables to the href attribute using either data binding notation or interpolation.

    <ng-container *ngFor="let plan of plans">
      <a href="#{{ plan?.planCode }}_details">{{ plan?.PlanName }}</a>
    </ng-container>
    

    Update

    I am not sure what you're exactly after, but to combine both the questions, you could do something like following

    <p>User 1 is enrolled in 
      <ng-container *ngFor="let plan of plans; let last=last">
        <a href="#{{ plan?.planCode }}_details">{{ plan?.PlanName }}</a>
        <ng-container *ngIf="!last">
          ,&nbsp;
        </ng-container>
      </ng-container>
    </p>
    

    In this case you do not need the additional variable planNames.