在 Angular 2 中选择复选框时将项目数组添加到文本区域

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

我在 for 循环中有一个复选框列表,因为我 select 一个名称需要显示在文本区域中,所以当我保持 selecting 时,它们需要被添加,因为我deselect 他们需要被删除。我可以添加项目,但一次只能显示一个。我无法在文本区域中显示数组。我在尝试删除 deselected 项目时也遇到了问题。请帮忙。下面是我的代码....

复选框

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

文本区

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

组件方法

public displayItemNameList = [];

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

也帮我解决如果我要取消选择,我该如何从数组中删除项目名称。我试图为此检查 indexof 不确定是否有帮助。请指导....

Here 是关于 stackblitz 的一个例子,说明我会如何处理它。

主要有以下几点:

  1. 您使用复选框在代表所选项目的数组中添加或删除项目。
  2. 然后,您为组件中的另一个变量创建一个 getter,负责发送数组的字符串表示形式(例如,您可以使用 toString() 进行基本显示)。
  3. 最后,将此字符串变量绑定到文本区域。

希望对您有所帮助

<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

在你的 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
}