How to display image in angular?

How to display image in angular?


<div><img  class="images" ng-src="{{./resources/img/new.png}}"/></div>

<div><img  class="images" src="./resources/img/new.png"/></div>```

Upvotes: 9

Views: 59253

Answers (4)

Install serve-static :

npm install --save @nestjs/serve-static

Then, in app.module.ts (Nestjs) :

import { ServeStaticModule } from '@nestjs/serve-static';
import {  resolve } from 'path';  
.... 
@Module({
  imports: [....,
        ServeStaticModule.forRoot(
      (() => {
        const publicDir = resolve('uploads');
        return {
          rootPath: publicDir,
          serveRoot: '/public',
          exclude: ['/api*'],
        };
      })()
    ),]

Use resolve('mydir') to url where storage files and view ex. http://localhost:3000/public/image.png

Upvotes: 0

Vinod Bokde
Vinod Bokde

Reputation: 338

Consider the Simple and Easy solutions for your problem.

The more complex code will confuse further.

Angular js file:

$scope.imageAddress='resources/img/new.png';

// The Path has to be exact.
// Check your project folder hierarchy for that.

HTML file:

<body ng-app = "myApp">
    <div ng-controller="myController">
        <img alt="" ng-src="{{ imageAddress }}" />
    </div>
</body>

And Your path will be according to the HTML file in which you had written your Image source code.

eg:- If your ng-src is in Index.html path: resources/index.html

and your new.png is in path: resources/views/images/new.png

then $scope.imageAddress='views/images/new.png';

One more thing: Prefer ng-src over src.

Upvotes: 1

Chanaka Weerasinghe
Chanaka Weerasinghe

Reputation: 5742

How the Angular CLI Deals with Images

Remember when we used the npm run build or ng build --prod command? Angular CLI moved all of our assets into the dist folder. It will do the same when it sees that there are images inside the assets folder.

All we have to do is reference these images in our templates with a path that starts inside the src folder.

For instance, if we have an image at src/assets/img/logo.png, we would add this to our template:

template: <img src="assets/img/logo.png"> Adding An Image to the Assets Folder The assets folder that the Angular CLI generated for us is the perfect place to use for storing images.

Let's go grab the Angular logo from angular.io.

https://angular.io/assets/images/logos/angular/[email protected]

Upvotes: 5

Velusamy Venkatraman
Velusamy Venkatraman

Reputation: 736

Learn angular template binding (https://angular.io/guide/template-syntax). If you have image in local like (./resources/img/new.png) you can use normal html source tag

<img  class="images" src="./resources/img/new.png"/>

Or your image comes from server or dynamically that time you have to bind that like

img = this.imageSource
<img  class="images" src={{img}}/> or
<img class="images" [src]="img"/>

Upvotes: 7

Related Questions