Nirojan Selvanathan
Nirojan Selvanathan

Reputation: 11164

How to refer images in Angular HTML page

I'm using angular 5 and web pack (Not angular CLI). This is my folder structure.

-src
 | -app
    | - subfolder
        | - subfolder
            | - componenet.html
 | -assets
   | - test.png

When referring to this image in my HTML file I have to use a lot of backslashes. The following code segment shows an example.

<div>
    <h1>Menu Page</h1>
    <img src="../../../../../assets/test.png">
</div>

Is their a more practile way to do this in angular ? Im using file-loader to bundle the images to the dist folder and html-loader for html pages.

Upvotes: 0

Views: 488

Answers (1)

Antoine
Antoine

Reputation: 76

In your project's angular.json file make sure that your project -> architect -> build -> options -> assets config is setup properly:

{
  "build": {
   "architect": {
       "options": {
            ...

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

Then in your template you should be able to do:

<div>
<h1>Menu Page</h1>
<img src="/assets/test.png">

EDIT (if not using angular-cli, which is strongly suggested):

in your webpack.config.js

  const path = require('path');

  module.exports = {
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist')
    },
    module: {
      rules: [
        ...
       {
         test: /\.(png|svg|jpg|gif)$/,
         use: [
           'file-loader'
         ],
         options: {
          outputPath: 'assets',
        },
       }
      ]
    }
  };

Upvotes: 2

Related Questions