Search code examples
angularcheckboxtextareaangular2-templateangular2-inputs

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


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


Solution

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