1

I want to assign model value from the current loop index, but its not working . any idea about this

https://plnkr.co/edit/YccCBF98vCetWXJa1UJX?p=preview

  <p *ngFor="let person of peoples; let i = index;">
  
  <input type="hidden" [(ngModel)]="person.displayOrder" [value]="i+1" />
  
  </p>
Sarath
  • 126
  • 1
  • 7

2 Answers2

3

For this we need to create a custom pipe :

HTML :

<div>
    <h2>Hello {{name}}</h2>
    <p *ngFor="let person of (peoples | changeOrder); let i= index;">
        {{person.name}} <input type="text" name='{{i}}' [(ngModel)]="person.order" />
    </p>
</div>

Custom Pipe :

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'changeOrder' })
export class changeOrder implements PipeTransform {
  transform(allPeoples) {
    return allPeoples.map( ( val ,index) => { val.order = index; return val; });
  }
}

NgModule :

@NgModule({
  imports: [ BrowserModule,FormsModule ],
  declarations: [ App , changeOrder ],
  bootstrap: [ App ]
})

Hers is the link to Plunker , please have a look.

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
0

Try to use ngValue instead of value. Take a look at the answer I gave here.

Edit

Sorry, ngValue is for option on select and you have an input. I tried your initial code and is working fine. What is your error?

BogdanC
  • 2,746
  • 2
  • 24
  • 22
  • Getting this error message: Can't bind to 'ngValue' since it isn't a known property of 'input'. – Sarath Aug 02 '17 at 13:23