Angular 2/4 img src

时间:2017-07-03 19:26:44

标签: angular

我只是想在组件中渲染图像。我似乎找不到合适的答案。

有人能指出我正确的方向吗?

环境:

angular / cli 1.1.2

节点8.1.0

OS win x64

angular -v 4.2.5

我累了(HTML):

<img [src]={{imgUrl}} />
<img [src]="imgUrl" />

<img src={{imgUrl}} />
<img src="imgUrl" />

<img ng-src="imgUrl" />

<img src="assets/images/img.jpg" />
<!-- and a few more -->

使用.ts文件:

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  imgUrl = "";

  constructor() {}

  ngOnInit() {
     this.imgUrl = 'assets/images/img.jpg';
     // i have also tried
     // ~/assets/...
     // ./assets/...
     // etc
  }


}

项目结构:

src
--app
----home
------ts-files
--assets
----images
------img.jpg

我还尝试将文件从资源移动到同一个ts文件夹和其他一些地方。

但我只得到相同的404错误。

获取http://localhost:4200/assets/images/img.jpg 404(未找到)

更新

.angular-cli.json内容(自动生成):

{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "Test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

3 个答案:

答案 0 :(得分:3)

您确定<img src="/assets/images/img.jpg">不起作用吗?注意其中的前导'/'。当您使用Angular CLI时,如果运行ng build,它应该在项目中使用构建的静态Web文件创建dist目录。您能否确认assets/images/img.jpg文件位于ng build生成的输出中?

答案 1 :(得分:0)

@ J.D提供的答案。在评论部分。

.angular-cli.json中,将包含图像的目录名称添加到资源。例如:要添加的目录是图片"assets": ["assets", "images" ]

  

正如@stealththeninja注意到的那样,你的angular.cli.json错过了图像。尝试添加它 - “资产”:[“资产”,“图像”

答案 2 :(得分:-1)

你试过试试吗? <img ng-src="{{imgUrl}}" /> https://docs.angularjs.org/api/ng/directive/ngSrc