角度7:* ngFor具有组件并传递变量参数

时间:2019-06-26 03:33:50

标签: angular ngfor

========

更新:看来我需要两件事:

  1. 使用方括号[src] =“ someimg.png”或src =“ {{someimage.png}}”“
  2. 我忘了删除html中的原始图像源,因此每次迭代都会显示它。噢!

感谢您的回答和评论!

========

我有一个用于父级组件web-portfolio.html的投资组合项目,它从web-portfolio.ts获取数据。

我正在尝试通过* ngFor循环中的web-portfolio.ts文件中的数组传递数据。

<app-portfolio *ngFor = "let site of this.sites" name = "site.name" img = "site.img" description = "site.description" link = "site.link"></app-portfolio>

app-portfolio组件具有以下输入:

export class PortfolioComponent implements OnInit {

  isOpen: boolean = false;
  @Input() name: string;
  @Input() img: string;
  @Input() description: string;
  @Input() link: string;

}

但是我没有得到正确的输出,而是收到了初始数组的三个值;

export class WebPortfolioComponent implements OnInit {
 sites = [
    {
     "name":"Site A",
     "description": "Lorem Ipsum",
      "img":"/web/sitea.png",
      "link":"http://sitea.com"
    },
    {
     "name":"Site B",
     "description": "Lorem Ipsum",
      "img":"/web/siteb.png",
      "link":"http://siteb.com"
    },
   {
     "name":"Site C",
     "description": "Lorem Ipsum",
      "img":"/web/siteC.png",
      "link":"http://siteC.com"
    },
  ];
}

 // OUTPUT => Blank, blank, blank

我在做什么错了?

portfolio.component.html:

<div class = "portfolio-item">
  <div class = "portfolio-thumb">
    <a (click) = "this.isOpen = !this.isOpen">
      <img src = "" alt = ""/>
    </a>
  </div>
  <div class = "portfolio-full" [ngClass] = "{'port-show':this.isOpen}">
    <div class = "portfolio-full-image" (click) = "this.isOpen = !this.isOpen">
      <img src = "{{this.img}}">
      <div class = "portfolio-description">
        {{this.description}}
      </div>
    </div>
  </div>
</div>

3 个答案:

答案 0 :(得分:2)

您需要为属性组件name = "{{site.name}}"添加{{}}

<app-portfolio *ngFor = "let site of this.sites" name = "{{site.name}}" 
 img = "{{site.img}}" description = "site.description" link = "site.link"></app-portfolio>

https://stackblitz.com/edit/angular-ns1qli

HTML更新仍然有效

https://stackblitz.com/edit/angular-input-parameter?file=src/app/portfolio.html

答案 1 :(得分:1)

只需将组件像属性绑定一样包装在Angular中

<app-portfolio *ngFor = "let site of this.sites" [name] = "site.name" [img] = "site.img" [description] = "site.description" [link] = "site.link"></app-portfolio>

答案 2 :(得分:0)

img是html属性,因此不能与@Input一起使用,因此请改用[image],请检查以下示例。

Stack Blitz Demo