sammy gimnyigei
sammy gimnyigei

Reputation: 11

*ngFor not working with my array when displaying on template

I have tried display content using *ngFor both on a table and select components but nothing seems to work. could you please assist? on my component i have this

public get locs(): Address[] {
        var addr: Address[] = [{ id: 0, priceQuickDelivery: 0, DeliveryTime: "3456", name: "samwel", price: 0 }];
        return addr;
    }
changeLocation(id: any) {
        console.log("locations id", id);

        this.currentLocation = this.locations.filter(f => {
            f.id == id
        })[0];
        console.log("selected location:", this.currentLocation);

    }

and on my template i have this:

<table>
        <tbody>
            <tr *ngFor="let loc of locs">
                <td>value</td>
                <td>{{loc.name}}</td>
                <td>{{loc.id}}</td>
            </tr>
        </tbody>
    </table>

    <div >
        <select #SelectLocation (change)="changeLocation(SelectLocation.value)">
            <option value="0">Choose Location</option>
            <option *ngFor="let location of locs"> {{location}}</option>
        </select>
    </div>

my Address model is as follows:

export class Address {
    public id: number;
    public name: string;
    public price: number;
    public priceQuickDelivery: number;
    public DeliveryTime: string;
    constructor() { }
}

my output is as follow enter image description here

enter image description here

Upvotes: 1

Views: 1747

Answers (2)

Shlok Nangia
Shlok Nangia

Reputation: 2377

As location is a list of objects

Using this <option *ngFor="let location of locs"> {{location}}</option> will not display anything as location is a object and you might be getting [Object, Object]

Instead use properties of location not the location itself i.e.

<option *ngFor="let location of locs"> {{location.name}}</option>

Surely it will populate your list

Upvotes: 0

Hien Nguyen
Hien Nguyen

Reputation: 18975

You did not use property in *ngFor change to

<option *ngFor="let location of locs" value={{location.id}}> {{location.name}}</option>

Stackbliz demo https://stackblitz.com/edit/angular-ivy-6p9fbh

Upvotes: 0

Related Questions