skip to Main Content

I’m new to Angular and I am struggling to bind data from list-articles to another component called Article. I tried for several hours and it does not work.

<!--list-articles.component.html-->

<ul>
    <li *ngFor="let a of Articles;"><article [Titre]="a.Titre" [Description]="a.Description" [Banniere]="a.Banniere"></article></li>
</ul>

//list-articles.component.ts
export class ListArticlesComponent {
  Articles:ArticleComponent[] = [{Titre:"article1",Banniere: ".../imgs/images.png", Description:"Voici l'article1"},
  {Titre:"article1",Banniere:".../imgs/images.png", Description:"Voici l'article1"},
  {Titre:"article1",Banniere:".../imgs/images.png", Description:"Voici l'article1"}];
}

//ArticleComponent.ts
export class ArticleComponent {
  @Input()
  Titre:string ="";
  Banniere:string="";
  Description:string="";
  
}

<!--article.component.html-->
<div>
    <img />
    <h4>{{Titre}}</h4>
    <p>{{Description}}</p>
</div>

I changed the syntax of the properties in list-articles.component.ts a dozen times and it does not display anything (see image below). The expected result should be the data in list-articles.component.ts displayed in the ul. I would really appreciate if someone could explain to me what I’m doing wrong.

enter image description here

edit: this should be the result

This should be the result:

Thank you and have a nice day 🙂

2

Answers


  1. You are using let asdf of Articles which means, Article’s properties should be accessed by asdf object but you are trying to access it using a object which is wrong.

    Correct template would be:

    <ul>
        <li *ngFor="let asdf of Articles;"><article [Titre]="asdf.Titre" [Description]="asdf.Description" [Banniere]="asdf.Banniere"></article></li>
    </ul>
    
    Login or Signup to reply.
  2. The problem is at the ArticleComponent.

    // ArticleComponent.ts
    export class ArticleComponent {
      @Input()
      Titre:string ="";
      Banniere:string="";
      Description:string="";
      
    }
    

    The @Input decorator must be in the same line as the property, and must pre present at every property:

    // ArticleComponent.ts
    export class ArticleComponent {
      @Input() Titre:string ="";
      @Input() Banniere:string="";
      @Input() Description:string="";
    }
    

    I really suggest you reading the Angular docs starting from the Getting Started:

    https://angular.io/guide/what-is-angular

    Also as suggested by @joka00 you should not use existing html tags names for components.

    Angular suggestions you adding an app- prefix to your components to avoid names colisions. That’s the default behavior of ng g component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search