How to Load Image (And Other Assets) in Angular an Project

How to load image (and other assets) in Angular an project?

I fixed it. My actual image file name had spaces in it, and for whatever reason Angular did not like that. When I removed the spaces from my file name, assets/images/myimage.png worked.

What is the correct way to load images (and other assets) in an Angular 11 project?

inside angular.json you have this part of configuration:

"assets": [
"src/assets"
],

When ng build --prod is run, the paths you included here, will be included in the final build as well, so you will be able to access them on the server. You can add any other folders as well. That's why the correct form of pointing to files inside your angular app is using the absolute path like this: src: url('/assets/fonts/NunitoSans-Bold.woff') format('woff');

Angular 6 Failing To Load Images From Assets

<img class="logo" src="assets/image.png">

This is the right path, probably something else went wrong.

check that the image name or if its jpeg.
maybe you added a new folder in the assets folder ? , like images if so the code should look like this

<img class="logo" src="assets/image/image.png">

unable to load image from assets folder in angular

A few things needs to be considered:

  1. ViewChild binds to the view, so its best to await for the view to finish initialization (use ngAfterViewInit hook), but ngOnInit will also work (it is just if you would need in future to consider offsets etc for drawing into canvas it might bite you:)

  2. Image loading is an async task, you need to leverage onload hook before you attempt to draw the image

  3. Use "/assets/.." urls to avoid issues

Updated code:

export class CanvasComponent implements OnInit {

@ViewChild("crfCanvas", { static: true }) crfCanvas: ElementRef;

constructor() { }

ngAfterViewInit() {
let canvas = this.crfCanvas.nativeElement;
let ctx = canvas.getContext("2d");
let img = new Image();
img.src = "/assets/aCRF-PRV111_CLN-001 v1.4-images/aCRF-PRV111_CLN-001 v1.4-blank_0.jpg";
img.onload = () => {
ctx.drawImage(img, 10, 10, 250, 250);
}
}

}

Stackblitz: https://stackblitz.com/edit/angular-v5tqbn

Image Not Loading in Angular 9

After several tries I got it. Since the assets are configured to sit in src/assets

"assets": [
"src/favicon.ico",
"src/assets"
]

This is how you should add the path:

<div>
<img src="./assets/img/menu.png" alt="LOGO">
</div>


Related Topics



Leave a reply



Submit