Include the root prefix in angular.json

Within my angular.json file, I am utilizing the following code snippet:

"root": "admin/",
  "sourceRoot": "src",
  "prefix": "app",
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "baseHref": "/admin/",
        "deployUrl": "/admin/",
        "outputPath": "dist/front/admin",
        "index": "src/index.html",
        "main": "src/main.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "tsconfig.app.json",
        "aot": true,
        "assets": [
          "src/favicon.ico",
          {
            "glob": "**/*",
            "input": "src/assets/",
            "ignore": ["**/*.svg"],
            "output": "/assets/"
          }
        ],
...

However, I am encountering an issue when trying to display images. The following code does not seem to work:

 <img src="/assets/images/test.png">

In contrast, this code functions as expected:

<img src="admin/assets/images/test.png">

I would like to know how to set the "admin/" prefix in angular.json for each asset. Help would be appreciated.

Answer №1

A handy way to modify the src attributes of all img tags is by creating a custom Directive.

Follow these steps:

  1. Create a new directive using the Angular CLI:
ng generate directive set-img-src-prefix
  1. Configure the newly created directive as follows:
import {Directive, ElementRef} from '@angular/core';

@Directive({
  selector: 'img' // targets all img tags
})

export class SetImgSrcPrefixDirective {
  constructor(public ref:ElementRef) {
    // make global changes here
  }
}
  1. Finally, don't forget to include the directive in your app.module.ts:
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';
import {SetImgSrcPrefixDirective} from './set-img-src-prefix.directive'; // import the directive

@NgModule({
  declarations: [
    AppComponent,
    SetImgSrcPrefixDirective // add directive here
  ],
  imports: [
    BrowserModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interface in Typescript that extends Object with keys that are dynamically assigned

In my Typescript code, I encountered an issue while trying to make my interface extend Object when using an indexer with a key as a string. When I do not extend Object, everything works fine except that the intellisense does not provide suggestions for th ...

Utilizing Vue 3 to transform an item within a list by referencing its index

Storing the element's index in a global variable is causing issues when trying to individually edit each of them. Adding multiple elements with similar properties but being unable to edit them separately due to alterations affecting the rest is a chal ...

Using various functions to set values in AngularJS

I am facing a small issue where I am calling a service method within one function and then trying to access the values from that function in another function within the same controller. However, when attempting to access the values, it shows that they are ...

The terser-webpack-plugin and uglifyjs-webpack-plugin are both powerful tools for optimizing

WebPack 4 now utilizes the terser-webpack-plugin in production mode or when the -p argument is specified, which essentially means including --optimize-minimize --define process.env.NODE_ENV="production". This plugin is responsible for minimizing ...

Creating a function that can map various types of objects to a single type

type ShapeA = { id: number; length: string; width: string; height: string; } type ShapeB = { id: number; side1: string; side2: string; side3: string; } type Shapes = (ShapeA | ShapeB)[] type MappedShape = { id: number; dimension1: st ...

"An error has occurred: ENOENT - The specified file or directory does not exist, cannot create directory" on the live website

I am facing an issue on my website where I need to create a folder and save some files in it. While the code works perfectly fine locally, once deployed on render, I encounter the following error: Error: ENOENT: no such file or directory, mkdir '/opt/ ...

Error encountered in Selenium WebDriver due to JavascriptException

Attempting to execute JavaScript within Selenium WebDriver has resulted in an error. The script was stored in a string variable and passed to the `executeScript()` method. Upon running the script, a `JavascriptException` occurred. Below is the code snippet ...

Sending forms through the .NET platform

On my .NET page, I have implemented client-side validation for a submit button within the form element. var register = $('#<%= Register.ClientId %>'); register.click(function(){ validation.init(); return false; }); Disabling the f ...

What is the best way to utilize regex for replacing a string within Node.js environment?

I'm struggling with updating the string in my code. Essentially, I have a .php file and I want to modify some constants using the replace package. The output of my current code is: // Current Output define('DB_NAME', 'foo'); // ...

Updating an HTML value based on the selected option using JavaScript

I'm working on a form that included a select element: <select class="form-control"> <option>10 pc</option><!--1 USD --> <option>20 pc</option><!--2 USD --> <option>50 pc</option><!--3 USD ...

What is the solution to the TypeScript error stating that there is no index signature with a parameter of type 'string' on the 'Object' type?

While working on an Angular project, I came across an issue when writing a Typescript function for a service. The error message stated: "Element implicitly has an 'any' type because expression of type 'string' can't be used to inde ...

Unusual behavior involving the selection of $stateParams

Seeking a solution for updating angular-ui route parameters based on select field changes. Issue: The route successfully updates with the selected parameter, but the select field does not reflect the change in option selection. Check out the Plunkr. Clic ...

Utilizing AWS SDK (S3.putObject) to transfer a Readable stream to Amazon S3 using node.js

I am aiming to successfully send a Readable stream to S3. However, I have encountered an issue where the AWS api only seems to accept a ReadStream as a stream argument. When using a ReadStream, everything works as expected, as shown in the following code ...

Unexpected behavior: jQuery AJAX parameters not properly received by PHP script

Here is some javaScript code that I have: const getReport = { jobID: $('#jobID').val(), startDate: $('#summaryStart').val(), endDate: $('#summaryEnd').val(), tableType: 'Summary', }; $.ajax({ url ...

Primeng - Displaying names in editable datatable with multiSelect feature

Lately, I have been exploring primeng and I am interested in creating an editable table that includes a multi-select column. After some experimentation, I managed to achieve this result. However, my issue is that I want the winners field (which contains a ...

Can a map key value be converted into a param object?

I have a map containing key-value pairs as shown below: for (let controller of this.attributiFormArray.controls) { attributiAttivitaMap.set(controller.get('id').value, { value: controller.get('valoreDefault').value, mandatory ...

Utilizing event binding with ngForTemplate in Angular 2

Imagine having a straightforward list rendering component: import {Input, Component } from 'angular2/core' @Component({ selector: 'my-list', template: ` <div *ngFor='#item of items' (click)='onItemClicked(i ...

Capturing all input values from an HTML form in Node.js using Express

I've encountered an issue where I am unable to retrieve the value of a checkbox labeled "1" in the provided HTML code through req.body. It seems that only the username and password values are included in the req.body, while the passwordConfirm is miss ...

Ways to block past dates on bootstrap date picker starting from the current date and how to prevent dates beyond 90 days in the future from being selected on the

I am currently facing an issue with disabling previous dates from the current date in my code. While the functionality works well for the "From Date" date picker, I am having trouble implementing the same restriction for the "To Date" date picker after 90 ...

Detecting When a User Reaches the Bottom of the Screen in REACTjs

My goal is to monitor when the user reaches the bottom of the screen and then trigger a function to load more data. Within my app.js file, I have a Products component that handles the data fetching. The Products component is enclosed in a div with a class ...