1

So I'm building a project using Angular 4, I have a bunch of images in my assets folder and I have an array of objects in my app.component.ts file that is trying to reference them.

The directory is set out like this

src
| app
   | app.component.ts
   | app.component.html
   | ...
| assets
   | robbie.jpg
   | ...

The ts file includes the image references like this,

export class AppComponent {

// array of contact objects
contacts = [
{
  name: "Robbie Peck",
  image: "../assets/robbie.jpg",
  email: "XXXXXXXX",
  phone: "XXXXXXX",
  role: "Software Developer",
  address: "XXXXXXX",
  notes: "XXXXXXX",
  selected: false
},
...
]
}

And in app.component.html, I'm trying to reference this image through an img tag like this

<img src={{contacts[0].image}}>

It isn't however working- the console says that this path can't be found and won't display the robbie.jpg image within the assets folder on the page.

How do I do this? How do I normally reference images within components in Angular 4?

3 Answers3

1

Try this syntax: img src="assets/robbie.jpg"

Angular know assets folder path, we don't require to tell explicitly.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
0

Assuming you are using the ng serve command to run your application, the assets folder will be on the same level as the generated javascript and html output. Simply:

image: "assets/robbie.jpg"

should work.

tony
  • 1,274
  • 1
  • 11
  • 27
0

try this

export class AppComponent {
    public contacts = [
    {
      name: "Robbie Peck",
      image: "../assets/robbie.jpg",
      email: "XXXXXXXX",
      phone: "XXXXXXX",
      role: "Software Developer",
      address: "XXXXXXX",
      notes: "XXXXXXX",
      selected: false
    },
    ...
    ]
  }
chirag sorathiya
  • 1,223
  • 8
  • 29