Adding an array of items to textarea when selecting checkboxes in Angular 2

3.5k Views Asked by At

I have a list of checkboxes in for loop and as I select one the name needs to get displayed in a textarea so as I keep selecting they need to get added and as I deselect they need to be removed. I am able to add the items but dispay only one at a time. I am unable to display array in the textarea. Also I was facing issues while trying to remove the deselected items. Please help. Below is my code....

Checkbox

<div *ngFor="let items of itemList">
  <div class="xxx"><input type="checkbox" id="chk" name="checker" (click)="AddToTextArea(items.Name)" />
   {{items.Name}}
  </div>
</div>

Text Area

<textarea class="ttt" id="itemList" name="itemName" rows="5" [(ngModel)]="displayItemNameList"></textarea>

Component Method

public displayItemNameList = [];

AddToTextArea(iName){
  this.displayItemNameList.push(iName);
}

Also help me with If I am deseleciting how can I remove the item Name from the array. I was trying to check indexof for this not sure if that would be helpful. Please guide....

2

There are 2 best solutions below

1
On BEST ANSWER
<div *ngFor="let items of itemList;let i=index">
  <div class="xxx"><input type="checkbox" id="chk" name="checker{{i}}" (click)="AddToTextArea(items.Name)" />
   {{items.Name}}
  </div>
</div>


<textarea class="ttt" id="itemList" name="itemName" rows="5">
{{showselected()}}</textarea> // you can also iterate a list here with ngFor

in your component.ts,

displayItemNameList = [];

AddToTextArea(iName){
  if(this.displayItemNameList.indexOf(iName)>-1){
  this.displayItemNameList.splice(this.displayItemNameList.indexOf(iName),1);
  }else{
   this.displayItemNameList.push(iName);
  }

}

showselected(){
 this.displayItemNameList.toString(); // this is basic string representation of array
}
6
On

Here is an example on stackblitz of how I would to it.

The main points are the following :

  1. You use your checkboxes to add or remove items in an array representing your selected items.
  2. Then, you create a getter for another variable in your component responsible to send a string representation of the array (for example you can use toString() for a basic display).
  3. To finish, you bind this string variable to your textarea.

Hope that helps