Home > Software engineering >  How to work with variables from a loop in HTML and with a component property?
How to work with variables from a loop in HTML and with a component property?

Time:06-22

The data I work with (bosses[]) has a boss object with contains the key-value email which is an string. I want to create the anchor with that string in the HTML. Also note that there's a loop in HTML that allows to access to each boss in bosses[]. So how can I access to create an anchor with boss.email which it only exists in the HTML loop? Many thanks in advance, god bless you.

I've tried '<a [href]="mailto: boss.email"></a>' but doesn't work.

the html:

 <div   *ngFor="let boss of bosses" >
     <div >
         <div >{{boss.name}} </div>
         <div>{{boss.email}}</div>
         <a [href]="mailto:   boss.email"></a>
     </div>

The component:

import { Component, Input, OnInit } from '@angular/core';
import { boss} from 'interfaces'
    
@Component({
  templateUrl: 'boss-cell.component.html',
  selector: 'boss-cell',
})
export class BossCellComponent implements  OnInit {
  constructor() {}

  bosses: any[] =  [{
    email:       '[email protected]',
    name:        'kennedy',
  
  }]
  

CodePudding user response:

You're close! I think this is what you're looking for:

 <div   *ngFor="let boss of bosses" >
     <div >
         <div >{{boss.name}} </div>
         <a [href]="'mailto:'   boss.email">{{ boss.email }}</a>
     </div>

CodePudding user response:

You can use interpolation as Suraj already mentionned in the comments, or bind to a function creating the string. Depending on weather you are going to link other elements to the mail, you should pick the cleanest option for you.

Template

<div  *ngFor="let boss of bosses; let i = index">
  <div >
    <div >{{ boss.name }}</div>
    <a [href]="getMail(i)">{{ boss.email }}</a>
  </div>
</div>

Script

bosses: any[] =  [{
  email:       '[email protected]',
  name:        'kennedy',
}]

getMail(index: number) {
  return 'mailto:'    this.bosses[index].email
}
  • Related