Angular NgStyle : list image style

Viewed 153

i have an array like this with a name and an image path in my component.

 skills = [
    {name: 'HTML5', iconSrc: 'src/assets/images/html-5 min.png'},
    {name: 'CSS3', iconSrc: 'src/assets/images/css-3 min.png'},
    {name: 'UML', iconSrc: 'src/assets/images/hierarchical-structure min.png'},
    {name: 'Javascript', iconSrc: 'src/assets/images/javascript min.png'},
    {name: 'PHP', iconSrc: 'src/assets/images/php min.png'},
    {name: '.NET', iconSrc : 'src/assets/images/hashtag min .png'}
  ];

I want to make a loop where i can use the path in iconSrc in the style attribute "list-style-image" I tried this but it doesn't work

<li *ngFor="let skill of skills" [ngStyle]="{'list-style-image': 'url({{skill.iconSrc}})'}">{{skill.name}}</li>

Or something like this

<li *ngFor="let skill of skills" style="list-style-image: url("{{skill.name}}")">{{skill.name}}</li>

What can i do to fix that ?

3 Answers

You are nearly there! You want a dynamic value in your styles, so it is necessary to use [ngStyle]. style without brackets would not allow any dynamic values. The {{ curly brace syntax }} is only used outside of attribute-values.

This should work:

<li *ngFor="let skill of skills" [ngStyle]="{'list-style-image': 'url(\"' + skill.iconSrc + '\")'}">{{skill.name}}</li>

This is because you have white space in your images urls so you need to use quotes around the url. <li *ngFor="let skill of skills" [ngStyle]="{'list-style-image': 'url(\'' + skill.iconSrc + '\')'}">{{skill.name}}</li>

[style.listStyleImage]="'url(' + skill.iconSrc + ')'"

It's just a different way of achieving what others have posted, but I think it's a pretty clean approach. Make sure your iconSrc is correct... I doubt the path you are using will work, probably needs to be /assets/image.png

Related