Local Image Links Src using Angular 4

2.3k Views Asked by At

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

There are 3 best solutions below

0
tony On

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.

0
mangeshbhuskute On

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

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

0
chirag sorathiya On

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
    },
    ...
    ]
  }