Reputation: 5251
I'm confused. I'm trying to check in a loop if the outputted key is a mail key, if yes, I want to wrap the output into a <a>
tag to make the email clickable. Somehow it's not working and it's printing the whole content inside the div:
<div>{{contactInfo.key === 'mail_outline' ? '<a href="' + contactInfo.value + '">' + contactInfo.value + '</a>' : contactInfo.value}}</div>
Current result on the page:
{{contactInfo.key === 'mail_outline' ? '' + contactInfo.value + '' : contactInfo.value}}
I'm not sure if I understood the whole thing correctly. I'm coming from PHP and there I can do something like this. Can someone please explain me my issue?
Upvotes: 0
Views: 771
Reputation: 34425
If you surround the html elements inside the div
with quotes like you did, you are telling angular that the div
content is actually a text value. So it will end up displaying your condition as text.
You can add dynamic html by binding to innerHtml
property like suggested, however I find it cleaner to keep display logic in the template using one of the options below. Besides, they will avoid the extra overhead of calling a function every round of change detection
*ngIf
<div >
<a *ngIf="contactInfo.key === 'mail_outline'" href="{{contactInfo.value}}">{{contactInfo.value}}</a>
<ng-container *ngIf="contactInfo.key !== 'mail_outline'">{{contactInfo.value}}</ng-container>
</div>
Or use *ngSwitch, which will be more adequate if you've got several different cases
<div [ngSwitch]="contactInfo.key">
<a *ngSwitchCase="'mail_outline'" href="{{contactInfo.value}}">{{contactInfo.value}}</a>
<ng-container *ngSwitchDefault>{{contactInfo.value}}</ng-container>
</div>
Upvotes: 2
Reputation: 2663
Use angular Html binding. Update your html
<div [innerHtml]="getLink()"></div>
In your typescript
getLink(){
if(this.contactInfo.key === 'mail_outline')
{
return `<a href='${this.contactInfo.value}'>${this.contactInfo.value}</a>`;
}
else
{
return this.contactInfo.value;
}
}
Thanks.
Upvotes: 2