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

Set*_*eth 5 angular2-forms angular2-directives angular

我有一个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" />
Run Code Online (Sandbox Code Playgroud)

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

zone.js:569 Unhandled Promise rejection: Template parse errors:
Can't bind to 'ng-src' since it isn't a known property of 'img'.
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*eño 13

您可以使用[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[];
    //...
}
Run Code Online (Sandbox Code Playgroud)

在您的模板中

<div *ngFor="item in listItems">
    <img [attr.src]="item.imagePath" width="1" height="1" />
</div>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!