bhavsar japan
bhavsar japan

Reputation: 125

NgFor on Object + Create NgModel for each property in NgFor

I am facing issue while creating a ngfor on object and my ngfor contains ngModel of each property

Here is the code:

<div *ngFor="let key of objectKeys(todo)">

          <ion-item *ngIf="getObjectDataType(key) == 'String' && key != 'Description'">
              <ion-label floating>{{key}}</ion-label>
              <ion-input type="text" [(ngModel)]="this['todo.' + key]"  [ngModelOptions]="{ standalone : true }"></ion-input>
          </ion-item>

          <ion-item *ngIf="getObjectDataType(key) == 'String' && key == 'Description'">
              <ion-label floating>{{key}}</ion-label>
              <ion-textarea [(ngModel)]="this['todo.' + key]"  [ngModelOptions]="{ standalone : true }"></ion-textarea>
          </ion-item>

          <ion-item *ngIf="getObjectDataType(key) == 'Date' && key != 'Description'" 
              style="margin-top: 15px;">
              <ion-label>{{key}}</ion-label>
              <ion-datetime displayFormat="MM/DD/YYYY hh:mm A" [min]="yesterDayStr"
                 [(ngModel)]="this['todo.' + key]"  [ngModelOptions]="{ standalone : true }"></ion-datetime>
          </ion-item>

 </div>

Expected model string in this ngModel is > todo.title

But property are not going to bind to the respective input

Thanks

Upvotes: 0

Views: 59

Answers (2)

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9774

Agree with @Sajeetharan, we don't need to use 'this' and try using 'todo[key]'.

<div *ngFor="let key of objectKeys(todo)">

          <ion-item *ngIf="getObjectDataType(key) == 'String' && key != 'Description'">
              <ion-label floating>{{key}}</ion-label>
              <ion-input type="text" [(ngModel)]="todo[key]"  [ngModelOptions]="{ standalone : true }"></ion-input>
          </ion-item>

          <ion-item *ngIf="getObjectDataType(key) == 'String' && key == 'Description'">
              <ion-label floating>{{key}}</ion-label>
              <ion-textarea [(ngModel)]="todo[key]"  [ngModelOptions]="{ standalone : true }"></ion-textarea>
          </ion-item>

          <ion-item *ngIf="getObjectDataType(key) == 'Date' && key != 'Description'" 
              style="margin-top: 15px;">
              <ion-label>{{key}}</ion-label>
              <ion-datetime displayFormat="MM/DD/YYYY hh:mm A" [min]="yesterDayStr"
                 [(ngModel)]="todo[key]"  [ngModelOptions]="{ standalone : true }"></ion-datetime>
          </ion-item>

 </div>

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222712

You should not use this in the template, Change your code as follows,

 <ion-item *ngIf="getObjectDataType(key) == 'String' && key != 'Description'">
              <ion-label floating>{{key}}</ion-label>
              <ion-input type="text" [(ngModel)]="['todo.' + key]"  [ngModelOptions]="{ standalone : true }"></ion-input>
 </ion-item>

Upvotes: 0

Related Questions