简体   繁体   中英

Angular 2 *ngFor nested loop

I have two classes: Produkt and Werbedaten. werbedaten class has a produckt array.

I want to expose a werbedaten array which has the Produkts array using *ngFor

export class Produkt {
    public artikelNummer: number;
    public hauptabbildung: string;
}

export class WD {
    public nummer: number;
    public name: string;
    public produkts: Produkt[];
}

export class AppComponent {
   produkts1: Produkt[] = [
   new Produkt(1, ''),
   new Produkt(2, ''),
   new Produkt(3, '')
 ];
 werbedaten: WD[] = [
   new WD(1, 'Muesli', this.produkts1)
 ];
 }

<div *ngFor="let werbe of werbedaten">
    {{werbe.nummer}} {{werbe.name}}
    <p *ngFor="let produkt of werbe.produkts">
        {{produkt.artikelNummer}}
    </p>
</div>

It shows error when I am doing this code.

Can any one help me?

I'm mostly guessing as to what your problem is because you don't mention what error you are getting.

I got your example to work by adding constructors to the classes Produkt and WD

For example

export class Produkt {
    public artikelNummer: number;
    public hauptabbildung: string;

    constructor(aArtikelNummer: number, aHauptabbildung: string){
        this.artikelNummer = aArtikelNummer;
        this.hauptabbildung = aHauptabbildung;
    }
}

In your example, without a constructor, the compiler spits our the following error:

Supplied parameters do not match any signature of call target.

This makes sense because without the constructor we haven't told the compiler how to instantiate a new Product with parameters.

Another Solution

If you don't want to define a constructor for your class you could also define the produkts1 property in your app component like so:

produkts1: Produkt[] = [
    {artikelNummer:1, hauptabbildung:''},
    {artikelNummer:2, hauptabbildung:''},
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM