Dhananjay Sakhare
Dhananjay Sakhare

Reputation: 494

What is difference when I write array name in square brackets in ngFor?

I am learning angular 2 and I was trying to write ngFor statement. When I passed data through inputs I accessed that input in my template as below: My main component (I'm passing products using productList input to ProductList component)

@Component({
    selector: 'inventory-app',
    template: `
    <div class="inventory-app">
   <product-list [productList] = "products" 
   (OnProductSelected) = "productWasSelected($event)">

   </product-list>
    </div>
    `,
    directives: [ProductList]
})
class InventoryComponent {
    products: Array<Product>
    constructor() {
        this.products = [new Product('NICEHAT'
            , 'A nice Hat'
            , '/resources/images/products/black-hat.jpg'
            , ['Men', 'Accessories', 'Hats']
            , 29.99),
        new Product('BLACKHAT'
            , 'A nice Black Hat'
            , '/resources/images/products/black-hat.jpg'
            , ['Men', 'Accessories', 'Hats']
            , 29.99)];
    }
}

I wrote following code for component ProductList:

@Component({
    selector: `product-list`,
    inputs: [`productList`],
    template: `<div *ngFor = "#product of [productList]">{{product}}</div>`
})

class ProductList {

}

Note that when I wrote array name productList like this : [productList]. The browser displayed output as

[object Object],[object Object],[object Object]

But when I wrote simply productList (without square brackets) browser returned:

[object Object]  
[object Object]  
[object Object]

Is there any explanation for this?

I am refering a book called ng-book2 to learn angular2 and this example has been taken from the book itself.

Thanks :)

Edit:

I observed that I couldn't read value of properties when I used [productList] e.g. {{product.name}} didn't display when I used square brackets. But it displays name when I write simple productList in ngFor

Upvotes: 0

Views: 733

Answers (1)

yurzui
yurzui

Reputation: 214007

[productList] means that you're creating array of array

And when you interpolate item of this array it will be stringified to string

[object Object],[object Object],[object Object]

While if you just use productList then angular will iterate over each item in productList. And since your array has 3 items it will render 3 div element

Let's say you have

productList = [{ name: 'name 1' }, { name: 'name 2' }]

In the first case when you use square breacers it can be written as follows:

*ngFor = "let product of [[{ name: 'name 1' }, { name: 'name 2' }]]"

while in the second case

*ngFor = "let product of [{ name: 'name 1' }, { name: 'name 2' }]"

Upvotes: 2

Related Questions