uzhas
uzhas

Reputation: 925

How to set dynamic data?

https://plnkr.co/edit/7hOOoJNYvx4K91yKWqYj?p=preview

I have this plunker that is not working. When i do this then is working:

  data = { Alice: {}, Bob: {}}

<div *ngFor="let person of people">
  <h1>{{person}}</h1>
  <div>
    Material
    <select [(ngModel)]="data[person].material" (ngModelChange)="materialChange($event, person)">
      <option *ngFor="let material of materials" [value]="material">{{material}}</option>
    </select>
  </div>
  <div>
    Colours
    <select [(ngModel)]="data[person].chosenColour">
      <option *ngFor="let colour of data[person].colours" [value]="colour">{{colour}}</option>
    </select>
  </di

How can i rewrite this because i need dynamic data, because i dont know how much data that i will have.. i dont need fixed value. Any suggestion?

Upvotes: 1

Views: 49

Answers (1)

AVJT82
AVJT82

Reputation: 73357

From what I am understanding that instead of

data = { Alice: {}, Bob: {}}

your people array length is n

people = ['Alice', 'Bob']

and you want it to reflect the data object.

So what you can do, is to map the people array and insert each string value as a property of your object, which itself holds an empty object:

this.people.map(x => this.data[x] = {})

This way data will now based on your example look like the hard coded data in your Plunker.

Upvotes: 1

Related Questions