Search code examples
angularngfor

Angular 7: *ngFor with a component and passing variable parameters


I have a portfolio item that is being used in a parent component, web-portfolio.html, getting data from web-portfolio.ts.

I'm trying to pass data from an array in the web-portfolio.ts file in an *ngFor loop.

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

The app-portfolio component has inputs for these:

export class PortfolioComponent implements OnInit {

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

}

But instead of getting the correct output, I receive three of the initial array's value;

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

What am I doing wrong?

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>

Solution

  • You need add {{}} for property component 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

    Update for your HTML still worked

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