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

I'm pretty new to Angular so I'm not sure the best practice to do this.
I used angular-cli and ng new some-project to generate a new app.
In it created an "images" folder in the "assets" folder, so now my images folder is src/assets/images
In app.component.html (which is the root of my application), I put
<img class="img-responsive" src="assets/images/myimage.png">
When I do ng serve to view my web application, the image does not display.
What is the best practice to load up images in an Angular application?
EDIT: See answer below. My actual image name was using spaces, which Angular did not like. When I removed the spaces in the file name, the image displayed correctly.

In my project I am using the following syntax in my app.component.html:
<img src="/assets/img/1.jpg" alt="image">
or
<img src='http://mruanova.com/img/1.jpg' alt='image'>
use [src] as a template expression when you are binding a property using interpolation:
<img [src]="imagePath" />
is the same as:
<img src={{imagePath}} />
Source: how to bind img src in angular 2 in ngFor?

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.

Angular-cli includes the assets folder in the build options by default. I got this issue when the name of my images had spaces or dashes.
For example :
'my-image-name.png' should be 'myImageName.png'
'my image name.png' should be 'myImageName.png'
If you put the image in the assets/img folder, then this line of code should work in your templates :
<img alt="My image name" src="./assets/img/myImageName.png">
If the issue persist just check if your Angular-cli config file and be sure that your assets folder is added in the build options.

Being specific to Angular2 to 5, we can bind image path using property binding as below. Image path is enclosed by the single quotation marks.
Sample example
<img [src]="'assets/img/klogo.png'" alt="image">

Normally "app" is the root of your application -- have you tried app/path/to/assets/img.png?

1 . Add this line on top in component.
declare var require: any
2 . add this line in your component class.
imgname= require("../images/imgname.png");
add this 'imgname' in img src tag on html page.
<img src={{imgname}} alt="">

You can follow the below steps in Angular 8+
Step 1: load the image as below in component
const logo = require('../assets/logo.svg').default as string;
#Component({
selector: 'app-show-image',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class ShowImageComponent implements OnInit {
logo = logo;
constructor() { }
ngOnInit() { }
}
step 2: Add the logic in html file
<img [src]="logo" [alt]="'logo'">
If launched without further configuration, you will see a strange error:
ERROR in src/app/app.component.ts(4,14): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i #types/node` and then add `node` to the types field in your tsconfig.
Do as suggested – add the #types/node typings to your project by running npm install #types/node and edit tsconfig.app.json to set:
"compilerOptions": {
"types": ["node"],
...
}
For more info
resource

It is always dependent on where is your html file that refers to the path of the static resource (in this case the image).
Example A:
src
|__assests
|__images
|__myimage.png
|__yourmodule
|__yourpage.html
As you can see, yourpage.html is one folder away from the root (src folder), for this reason it needs one amount of ../ to go back to the root then you can walk to the image from root:
<img class="img-responsive" src="../assests/images/myimage.png">
Example B:
src
|__assests
|__images
|__myimage.png
|__yourmodule
|__yoursubmodule
|__yourpage.html
Here you have to go u in the tree by 2 folders:
<img class="img-responsive" src="../../assests/images/myimage.png">

for me "I" was capital in "Images". which also angular-cli didn't like. so it is also case sensitive.
Some web servers like IIS don't have problem with that, if angular application is hosted in IIS, case sensitive is not a problem.

Try not give space while loading the images.
Instead of
<img src='assets/img/myimage.png' alt="">
try with string interpolation or Property Binding to load the source image as best practice.

Related

how to display images from nestjs server to Angular

When I upload a product from Angular side, It Post the product with imagepath, and the image is getting stored in the NestJs folder also, but I can not display product with it's image. The product is displaying at frontend but without it's image that is referenced and saved at the backend.
Anguar FrontEnd Code .ts
export class BooksComponent implements OnInit {
BookForm = new FormGroup({
_id: new FormControl(''),
name: new FormControl(''),
author: new FormControl(''),
price: new FormControl(''),
genres_name: new FormControl(''),
coverimage: new FormControl(''),
});
results?: Book[] = [];
searchedText: string = '';
constructor(
private readonly apiService: ApiService,
private router: Router
) {}
ngOnInit() {
this.apiService.getallbooks().subscribe((data) => {
this.results = data;
console.log(this.results);
});
}
Frontend html code.I'm getting all the information but not the image, here I'm providing src in img tag to display images
<div class="grid" *ngFor="let result of results">
<div class="blog-card spring-fever" style="padding: 0.5rem; z-index: 100">
<img
class="image"
src="http://localhost:3000/{{ result.coverimage }}"
alt=""
height="400px"
width="250px"
style="border: 1px solid red"
/>
This is the information of the Product that is coming from the backend
And when I try like this src="{{result.coverimage}}" or [src]="result.coverimage" I got error localhost:4200/assets/imagename not found(404). well that is obvoius!. because there is not such path, 4200 is for Angular. but I'm uploading the images at the backend assets folder which is located at localhost:3000/assets/, and we always upload files to backend for dynamic approach from database
In your highlighted part of your post you ask how to display the image, i.e you suspect the problem is in the frontend. However there is a missing part from the provided context. In the line where the html magic happens (The img tag src attribute).
There you are string interpolating a property called coverimage under the results object. We do not see what is inside the coverimage from your backend response in the frontend screenshot. If it is an id of a document then it will not be parsed correctly. The src attribute accepts:
APNG, AVIF, GIF, JPEG, PNG, SVG, and WebP. Or base64 (which seems not the case here).
When you have the image with one of the acceptable supported formats as stated in MDN correct you can map the property to the src attribute either via
1- string interpolation:
<img src="{{imagePath}}" />
2- property binding:
<img [src]="imagePath" />
The second way is more popular, but both work fine.
PS: it is a best practice and accessibility recommended to populate the alt="" property
If you are struggling to display the images coming from server, like I was, or you are struggling with the data that is coming NestJs. Then this might work for you as it worked for me.
So in my case I had a list of books and each book has path for its image. I was using ngFor and set the image src with the path. That is the right way. But the images were not visible and Network was showing images as text/html type. The actual issue here was not the type,the actual issue was in my URL.I had a folder in NestJs server by the name of assets,that is preset at root, and I had set the path for the images(in NestJs file upload code), like this ./assets/. That is also the correct way to set the destination folder.I was able to see the images at browser like this http://localhost:3000/imagename.png,and that means my server configured to server/serve my images over root URL that's why I can access them http://localhost:3000/imagename.png. But my api was returning images in a format that contains ./assets/ in the URL.
So with the following code
<div *ngIf="result.coverimage">
<img
class="image"
src="http://localhost:3000/{{ result.coverimage }}"
alt=""
height="400px"
width="250px"
style="border: 1px solid red"
/>
</div>
I am assuming that I'm hitting the Url like this http:localhost:3000/imagename.png. But actually Angular was seeing the URL like this http:localhost:3000/./assets/imagename.png. And this is note the correct URL Format. Urls don't work with . or ,.Also becasue my server is configured at root, this urlhttp;//localhost:3000/assets/imagename.png is also wrong.And root means that, whatever the thing is set at root, that is directly access able after your server's port number. Example http://localhost:YourServerPortNumber/TheThing_Set_at_Root.
So the solution for this issue is the following
src="http://localhost:3000/{{
result.coverimage.replace('./assets/', '')
}}"
With above .replace('./assets/', '') we are removing the ./assets/ and repalcing it with '' empty space. So now URL is in this formathttp://localhost:3000/imagename.png.

HTML image not loading the image src

Hey guys I'm making a TodoApp in react js, and I have a simple layout and I wanted to add a few images to the app. But when I add the images it is not loading that image.
Here is the code
import TodoList from './components/TodoList';
import imagem from './skate.png'
function App() {
return (
<div className="todo-app">
<TodoList />
<img src="imagem"/>
</div>
);
}
export default App;
And here is an image of what´s happening:
When using an bundler (like Parcel or Webpack) to handle images, you need to remember that the imported value is a variable.
You pass variables to props with { and }. Using a pair of " gives you a hardcoded string.
<img src={imagem} />
So,
In React.js (jsx) things don't work quite like HTML. WHat you are doing is importing the image from its location, by using:
import image from './skate.png';
and then, inside of your function.
If you import anything (image, css file, json file), for you to be able to use it you need to call it.
for example:
import JsonData from './data.json'
function App(){
return(
<div>
<JsonData/>
</div>
)
}
To call it.
SO in you case, you just need to replace
to
and it should work.
How about if you do this:
<img src={imagem} />
otherwise, it gets interpreted as a string and you have no http://../imagen on your site.
The problem with your code is that
"imagem"
is read as a String. To read it as an image, place {} around it as so:
{imagem}
"imagem" is string. Need variable {imagem].
when you use qoutes "" in jsx, it consumes it as a string and when you use {}, it consumes it as normal JS, so in your case, if you use
<img src={imagem} />
that would solve your problem

Hello i am having trouble getting the location of this picture to show in my react project

Its a JS File (FacePalm) I added the JSX curly braces but it still won't show up.
Here is the fiddle:https://jsfiddle.net/y68h9oj3/
I am trying to add a picture to my react project but it will not show up I tried hosting the picture on a web server it works but when I use local directory the image does not show up.
C:\Users\user\Documents\GitHub\Portfolio\Rework1\src Here is where the pictures location.
here is the src I have on the image tag
<img src="src/Aboutme.png" alt="Aboutme Header"></img>
C:\Users\user\Documents\GitHub\Portfolio\Rework1\src Here is where the pictures location.
<img src="src/Aboutme.png" alt="Aboutme Header"></img>
I expected the image to show up
Try importing your image and then use it with curly braces. Something like this
import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;
Refer https://facebook.github.io/create-react-app/docs/adding-images-fonts-and-files

Angular 5 - Can't output an Image using src?

I am using Angular 5 in an attempt to display an image that I have sat in a file 2 directories up from where I have the HTML, however I simply get the blank image box and an error in the console of:
GET http://localhost:4200/logo.jpg 404 (Not Found)
I am attempting to output via the code:
<img src="../../logo.jpg">
I have tested by placing a placeholder.it image within the src which worked perfectly... For some reason this will not?
If you are using #angular/cli you'd need to place your images under /src/assets/ in line with the .angular-cli.json asset configuration. You can then just use the image directly such as:
<img src="assets/pa-logo.jpg">
You can create additional folders under "assets" property in .angular-cli.json for additional control/organization as necessary:
"assets": [
"assets",
"foobar",
"favicon.ico"
],
Usage after you placed pa-logo.jpg in the this hypothetical foobar folder:
<img src="foobar/pa-logo.jpg">
Hopefully that helps!

Angular 4: Setting img src base href inside of innerHTML

In my Angular 4 app, I am using innerHTML to show description of the exercises which are in HTML format.
<li *ngFor="let exercise of exercises">
<div [innerHTML]="exercise.longDescription"></div>
</li>
These descriptions can also contain images
<img src="/file/na\6ad7k4ynon6yh2qcibcdqxwcey.jpg">
and that is where I am struggling because I need to set the base href for these images to localhost:8080 where my backend is. Angular is trying to get them from standard localhost:4200 (ng serve) so I am getting errors.
Any idea how to do that?
Found a solution, not sure if is the cleanest one but it gets the job done.
I created a function in my exercise model that adds environment.URL to the src (which is localhost:8080 for development and server's API for production).
public getHTML () {
return this.longDescription.replace(/<img src="([^"]+)">/, '<img src="'+environment.URL+'$1">');
}
and I access it like this
<div [innerHTML]="exercise.getHTML()"></div>
instead.
Environment const looks like this:
export const environment = {
production: false,
URL: 'http://localhost:8080'
};