我正在使用 Angular6 和 typeScript4.1.2 并尝试从 app.component.ts 加载图像并将其绑定(bind)到 app.component.html 但图像没有显示。奇怪的是,当我尝试直接在 app.component.html 中加载它时,图像是可见的。请帮助我理解 app.component.ts 中缺少的内容
app.component.ts:
declare function require(path:string):string;
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'angular-ui';
imagesrc = require('../assets/images/myimage.png');
}
app.component.html:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<img src={{imagesrc}} height="26"/>
<!-- <img src="../assets/images/myimage.png" height="26"/> -->
</a>
Test
</div>
</div>
</nav>
我尝试了几乎所有的组合来访问app.component.ts中的myimage.png,但这些都不起作用
imagesrc = require('../assets/images/myimage.png');
imagesrc = require('/assets/images/myimage.png');
imagesrc = require('assets/images/myimage.png');
我也尝试过使用自动完成功能,但 Visual Studio 代码在 ../assets/images/之后没有显示任何建议
并且资源路径已在 Angular.json 中设置
"assets": [
"src/favicon.ico",
"src/assets"
],
最佳答案
我认为您不需要 require
调用。尝试直接绑定(bind)路径
Controller
export class AppComponent {
title = 'angular-ui';
imagesrc = '../assets/images/myimage.png';
}
模板
<img [src]="imagesrc" height="26"/>
关于angular - 如何使用 TypeScript 4.1.2 在 Angular 6 中绑定(bind) img src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66489628/