Anna
Anna

Reputation: 35

how to display array in array angular 4

I want to display this list, but I could not access town attribute.

How could I fix my pb?

{ "id":"1",
      "name":"Hotel Ritz",
      "address":[
        {
         "country":"France",
         "town":"Paris",
        }
      ],
      "visited":true
    }
    { 
      "id":"2",
      "name":"The Plaza",
      "address":[
        {
         "country":"USA",
         "town":"New York"
        }
      ],
      "visited":false
    }

And what's the best method to display a checkbox to change the value of attribute visited? I tried this code but it does not work:

 <ul class="hotel-list">  
      <li ng-repeat="hotel in hotels">
        <span>{{hotel.name}}<span>
      </li> 
      <ul>
        <li *ngFor="let towm of hotel.address">{{address.town}}</li>
     </ul>
 </ul>

Upvotes: 0

Views: 2543

Answers (1)

Igor
Igor

Reputation: 62213

  • ng-repeat is angularjs syntax. *ngFor is angular syntax. You can't mix/match these, pick the correct syntax for the framework you are using.
  • In the HTML you reference towm which should be town
  • If you use let addressPart in your ngFor then you can reference that directly inside the scope of that element.
  • Your HTML syntax is not correct. ul contains li and not another ul element directly in it. You also have elements that don not have a matching closing tag.

<ul class="hotel-list">  
    <li *ngFor="let hotel of hotels">
        <span>{{hotel.name}}<span>
        <br/>
        Visited: <input type="checkbox" [(ngModel)]="hotel.visited" />
    </li> 
    <li>
        <ul>
            <li *ngFor="let addressPart of hotel.address">{{addressPart.town}}</li>
        </ul>
    </li> 
</ul>

Binding a value, like the visited property to a checkbox, is core concept of angular. In the above example I added 2 way binding. You can see more in the Template Syntax documentation.

Overall the angular documentation is very well written and has everything from tutorials to fundamental concepts to in depth API documentation. I recommend you check it out.

Upvotes: 3

Related Questions