Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 array of strings

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}}

like image 688
q.b Avatar asked Feb 22 '26 16:02

q.b


1 Answers

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);
like image 97
Omkar Dixit Avatar answered Feb 24 '26 05:02

Omkar Dixit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!