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>

2
  • What is your intention? You want to assign i+1 to person.displayOrder? Commented Aug 2, 2017 at 13:03
  • yes exactly. its a part of darg and drop ui Commented Aug 2, 2017 at 13:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Will you please set the plunker for this ?
the value setting , but not working the 2 way binding (Not changing the actual model value) , please checjk the updated plunker
@Sarath, Glad to hear that :) , will you please also accept the answer ?
@VivekDoshi why need pipe. can't we do it without pipe?
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?

1 Comment

Getting this error message: Can't bind to 'ngValue' since it isn't a known property of 'input'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.