简体   繁体   中英

Add prefix from root in angular.json

I have this code in angular.json:

"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/"
          }
        ],
...

But I have problem to display pictures. This doesn't work:

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

And this works fine:

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

How can I set "admin/" prefix in angular.json for each asset?

You can use a Directive to set prefix to src attributes of all img tags.

Steps are:

  1. Generate directive through cli :
ng generate directive set-img-src-prefix
  1. Config the newly generated directive like:
import {Directive, ElementRef} from '@angular/core';

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

export class SetImgSrcPrefixDirective {
  constructor(public ref:ElementRef) {
    // change anything you want globally here
  }
}
  1. And as the last step you have to add this directive in 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 here

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM