【问题标题】:Unable to use img ng-src (Can't bind to ng-src since it isn't a known property of img)无法使用 img ng-src(无法绑定到 ng-src,因为它不是 img 的已知属性)
【发布时间】:2017-10-08 12:25:56
【问题描述】:

我有一个带有 Webpack 的 Angular 项目,我正在尝试使用带有 ng-src 的 img 标签,根据此处的 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'.

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

【问题讨论】:

    标签: angular angular2-forms angular2-directives


    【解决方案1】:

    您可以使用 [attr.src] 输入绑定到原生 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>
    

    希望这会有所帮助!

    【讨论】:

    • 完美运行。谢谢!
    • 应该在哪里找到 HTML 标记的可绑定属性列表?在 angular.io 上搜索“img”并没有为我提供全面的文档..
    【解决方案2】:

    对我有用的是只使用 src。 示例:

        <td><img src="assets/{{elemento.foto}}" alt="(sin foto!)" class="img-responsive"/></td>
    

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 2021-03-20
      • 2018-02-12
      • 2021-10-24
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      相关资源
      最近更新 更多