简体   繁体   中英

How to correctly change style in *ngFor Items?

So I am using *ngFor in a component's HTML file to make quick interfaces for a recipe in a food app. I have a problem though. You see, when it's time to change key properties such as a background-image with a CSS property of url() change, I'm having a difficulty when it comes to applying those styles that involve dynamic name changes. (the recipe names in the *ngFor directive inside my HTML template.) These names vary.

Additionally, I'm retrieving this information from my component's ts file which is linked to a service where the JSON format array of objects is located.

I'm accessing these properties through dot notation for simple changes with a template like

<h1>{{recipe.recipeName}}</h1>

I'm trying to have a picture right under that header that matches the ones I have in my images folder (already downloaded) so I've tried something like...

 style.backgroundImage="{{'url(../../../imgs/food/startRecipes/' + **recipe.recipeName** +'.jpg)'}}"

which simply resulted in giving me errors in finding my files (where I know for a fact exist!) I get the 404 ERROR...

http://localhost:4200/imgs/food/guacamole.jpg **404 (Not Found)**

I also have some recipes in the JSON array that have a space in their name, and I cannot find a simple way to remove them... I tried using the replace method (I come from learning JavaScript) but it didn't quite work either.

Do you have any recommendations? I'm truly lost here. I'm still studying Angular, and I haven't quite caught up with pipes section in the course yet. However, I'm sure there's a much simpler way to do it in this case, maybe a ngStyle method, or something like that! Any help is greatly appreciated.

Go to angular-cli.json and look for something like this

{
"apps": [{
  "root": "src",
  "outDir": "dist",
  "assets": [
    "assets",
    "imgs",
    "favicon.ico"
  ]
}]
}

By adding the imgs folder name in the list of assets, you'll tell angular that it should look into the imgs folder for assets too for non routable Get requests. Otherwise the folder is ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM