简体   繁体   English

在 angular.json 中从 root 添加前缀

[英]Add prefix from root in angular.json

I have this code in angular.json:我在 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?如何在 angular.json 中为每个资产设置“admin/”前缀?

You can use a Directive to set prefix to src attributes of all img tags.您可以使用Directive为所有img标签的src属性设置前缀。

Steps are:步骤是:

  1. Generate directive through cli :通过cli生成directive
ng generate directive set-img-src-prefix
  1. Config the newly generated directive like:配置新生成的directive如:
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 :作为最后一步,您必须在app.module.ts添加此directive
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 { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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