angular - 无法使用 img ng-src(无法绑定(bind)到 ng-src,因为它不是 img 的已知属性)

标签 angular angular2-forms angular2-directives

我有一个带有 Webpack 的 Angular 项目,我正在尝试将 img 标签与 ng-src 一起使用,根据此处的 Angular 文档:

https://docs.angularjs.org/api/ng/directive/ngSrc

我正在尝试在图像源中设置一个变量,如下所示:

<img ng-src="assets/images/{{row.imagePath}}.png" width="1" height="1" />

但是,当我运行 ng serve 时,我在浏览器控制台中收到以下错误:

zone.js:569 Unhandled Promise rejection: Template parse errors:
Can't bind to 'ng-src' since it isn't a known property of 'img'.

我用 Google 搜索了一下,发现其他人使用 ng-src 时 Angular + Webpack 没有问题,所以我不确定为什么它在这个项目中不起作用。谢谢。

最佳答案

您可以使用 [attr.src] 输入绑定(bind)到 native html 属性。

在你的 component.ts 文件中

假设您有一个 ListItem 类型的项目列表,ListItem 类需要公开一个 imagePath 属性。像这样

export class ListItem {
    public imagePath: string;
    // ....
}

@Component({
  templateUrl: './your/template/example.html',
})
export class YourComponent {
    listItems: ListItem[];
    //...
}

在您的模板中

<div *ngFor="item in listItems">
    <img [attr.src]="item.imagePath" width="1" height="1" />
</div>

希望这对您有所帮助!

关于angular - 无法使用 img ng-src(无法绑定(bind)到 ng-src,因为它不是 img 的已知属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43882578/

相关文章:

angular - 未找到模块 : Error: Can't resolve '@angular/http' ?

angular - 从另一个组件 Angular 获取值 4

angular2-forms - Angular 2/Material - 应用到父 FormGroup 的自定义验证器未显示 md 错误

javascript - 如何在 Angular2 中获取(DOM)元素的宽度

使用 ng-content 的 Angular pass 模板引用

angular - 如何将 Angular 项目集成到 Squarespace 自定义模板中

angular - 属性指令 : Get an ElementRef width upon initialization

Angular 2 焦点表单元素

angular2-forms - Angular 2中的模板驱动形式和 react 形式有什么区别

javascript - 查询指令内的 View 变量不起作用