Angular CLI - 如何在可重用组件中引用图像路径

2024-02-15

需要帮助弄清楚如何将图像包含在另一个应用程序引用的可重用组件中。

例如,我有一个 Angular 应用程序,我们称之为 UI-Common,它包含通用组件;另一个 Angular 应用程序,我们称之为 Command-Center,它将使用这些通用组件。

在 UI-Common 中,有一个名为 my-control.component 的组件,其定义如下:

[my-control.component.html]

<div>
<img src="assets/images/myImage.png"/>
<div class"username" *ngIf="user">
    <p><strong>{{user.companyName}}</strong></p>
    <p>{{user.firstName + ' ' + user.lastName}}</p>
</div>

[我的控制.组件.ts]

import { Component, Input } from '@angular/core';

import { User } from '../../models/user';

@Component({
    selector: 'my-control',
    templateUrl: './my-control.component.html',
    styleUrls: ['./my-control.component.scss'],
})
export class MyControlComponent {
    @Input() user: User;

    constructor() {

    }
}

在 Command-Center 中,它将 UI-Common 添加为 package.json 中的依赖项。将创建一个 Command-Center 组件并使用 my-control.component,如下所示:

[应用程序模块.ts]

...
import { HomeComponent } from './home/home.component';
import { MyControlComponent } from 'ui-common';

@NgModule({
   declarations: [
      ...,
      HomeComponent,
      MyControlComponent,
      ...
   ],
   ...
})
export class AppModule { }

[home.component.html]

<my-control [user]=user></my-control>
<div class="homeContent">
    blah blah blah...
</div>

[主页.组件.ts]

import { Component } from '@angular/core';

import { User } from 'ui-common';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent {
  user: User;

  constructor() {
    this.user = new User();
    this.user.companyName = 'iHeartMedia';
    this.user.firstName = 'John';
    this.user.lastName = 'Smith';
  }
}

问题是从 Command-Center 运行时 my-control 上的图像根本无法加载。这似乎是因为命令中心中不存在正在使用的图像路径“assets/images/myImage.png”。我不想在命令中心的资产文件夹中保存图像的副本。如何正确处理公共组件中的图像?


发现这个 Angular CLI 功能请求:https://github.com/angular/angular-cli/issues/3555 https://github.com/angular/angular-cli/issues/3555

Angular 应用程序可以配置为将文件从相对文件路径复制到应用程序分发目录中的文件夹。这使我们能够从 node_modules 文件夹中访问图像,而无需手动将图像复制到本地资产文件夹中。

更新到最新版本的 Angular CLI (1.2.1) 后,我修改了 angular-cli.json 文件,如下所示:

{
...
"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        "version.txt",
        {
          "glob": "**/*",
          "input": "../node_modules/ui-common/src/assets/images",
          "output": "./assets/images"
        }
      ],
...
}

现在,Command-Center 应用程序可以访问 UI-Common 应用程序中的所有图像。

有关配置的更多详细信息,请参见此处:https://github.com/angular/angular-cli/wiki/stories-asset-configuration https://github.com/angular/angular-cli/wiki/stories-asset-configuration

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular CLI - 如何在可重用组件中引用图像路径 的相关文章

随机推荐