3

I'm using reactive form, I have 2 questions : I want to use a array of strings as an input that the user can change directly, I have a data model like this

export class Work {
    toDos: string[];  
}

Q1 : Is it ok to bind a input directly to an array of primitives or should I convert toDos in an array of object with a property name, and always use controls?

Q2 : I tried several think, but I can't find a simple way to make it working :

<div *ngFor="let item of toDos;let index = index;trackBy:trackByIndex;">
   <input [(ngModel)]="toDos[index]" placeholder="item" name="word{{index}}">
</div>

 <button (click)="addItem()" type="button">Add an 
Item</button>
<div *ngFor="let item of toDos">
  <label>{{item}}</label>
</div>

In the component.ts

toDos: string[] =["Todo1","Todo2","Todo3"];
trackByIndex(index: number, obj: any): any {
   return index;
 }
 addItem() {
   this.toDos.push('0');
 }

The add function works ok but the input is not bind and I don't get any errors, I can change the value of the input but it's not reflect on {{item}}

2
  • 1
    It works for me plnkr.co/edit/pOzYm4TNJqCbsnyC2jkk?p=preview Commented Jun 27, 2017 at 20:02
  • I found why it was not working, it was not working because it was inside a <form></form> I don't really know why though. It's ok now, thanks, I'd still be interesting to know if it's best practice to always use array of objects instead of array of primitives, and if it's better to use controlers with formControlName inside input instead of ngModel Commented Jun 27, 2017 at 21:41

1 Answer 1

3

Create a simple array as follows:

yourArray= new Array();

You can add elements to it easily using push function of the Array as follows:

yourArray.push(data);
Sign up to request clarification or add additional context in comments.

Comments

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.