根据 Angular 中的输入长度添加多个复选框

Add multiple checkboxes based on input length in Angular

目前,我的 Angular 应用程序中有一个复选框,我使用 HTML 代码绘制:

<input type="checkbox" id="box1" value="Apple">
<label for="box1"> Apple</label>

但是,我现在需要调整功能,使复选框的数量取决于数组输入。另外,数组的内容应该是复选框的标签。

例如:

如果我的数组是 arr = ['Apple', 'Mango','Banana'],我应该得到 3 个复选框(因为 arr 的长度是 3),如下所示:

我该怎么做?

使用 *ngFor 实现此目的

app.component.html

<div *ngFor="let item of arr;">
    <input type="checkbox" id="{{item}}" [value]="item " (change)="getItem($event)">
    <label for="{{item}}"> {{item }}</label>
</div>

app.component.ts

arr = ['Apple', 'Mango','Banana'];

getItem(item) {
   //check if the checkbox selected or not
   if(item.target.checked) {
      let value = item.target.value;
      console.log(value);
      //Do your thing here 
   }
}

希望对您有所帮助:)

有多种方法可以实现。

HTML

<div *ngFor="let item of array; let i = index">
    <input type="checkbox" [checked]="item.status" (click)="checked(i)">
    <label> {{item.name}}</label>
</div>

<div *ngFor="let item of arr;">
    <input type="checkbox" id="{{item}}" [value]="item ">
    <label for="{{item}}"> {{item }}</label>
</div>

Class

array = [
    { name: "Apple", status: true },
    { name: "Mango", status: true },
    { name: "Banana", status: true }
  ];
  checked(i) {
    this.array[i].status = !this.array[i].status;
  }
  arr = ["Apple", "Mango", "Banana"];

您还可以找到工作 link:stackblitz