【问题标题】:I have two lists in Checkbox,One I have already checked One is not checked initially我在复选框中有两个列表,一个我已经检查了一个最初没有检查
【发布时间】:2020-04-09 13:24:43
【问题描述】:

如果我从 xyz 中检查 somwething,我想在复选框中列出所有选中值,它应该被推送到列表中

{{项目}}

{{项目}}

【问题讨论】:

  • 到目前为止你做了什么?请显示您尝试过的一些代码。

标签: javascript arrays angular typescript checkbox


【解决方案1】:

您可以使用(change) 处理程序从数组中推送和删除项目。

<div *ngFor="let item of items">
  <input 
    type="checkbox" 
    name="{{item}}" 
    (change)="$event.target.checked ? selected.push(item) : selected.splice(selected.indexOf(item),1)">
  {{item}}
</div>

演示:https://stackblitz.com/edit/angular-hpdg3h

【讨论】:

    【解决方案2】:

    我创建了两个Demo:https://stackblitz.com/edit/angular-qfxe3j

    下面是最简单的一个,没有任何功能代码。

    menu.component.html

    <div style="display: inline-flex;">
      <div style="padding: 5px;border: 1px solid;margin-left: 30px;width: 120px;height: 200px;">
        <p>list 1</p>
        <ul style="list-style: none;">
          <ng-container *ngFor="let i of list">
            <li *ngIf="!i.checked">
              <input type="checkbox" [name]="i.val" [id]="i.val" [checked]="i.checked" (change)="i.checked = !i.checked">
              <label [for]="i.val">item {{i.val}}</label>
            </li>
          </ng-container>
        </ul>
      </div>
      <div style="padding: 5px;border: 1px solid;margin-left: 30px;width: 120px;height: 200px;">
        <p>list 2</p>
        <ul style="list-style: none;">
            <ng-container *ngFor="let i of list">
              <li *ngIf="i.checked">
                <input type="checkbox" [name]="i.val" [id]="i.val" [checked]="i.checked" (change)="i.checked = !i.checked">
                <label [for]="i.val">item {{i.val}}</label>
              </li>
            </ng-container>
          </ul>
      </div>
    </div>
    

    menu.component.ts

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-menu',
      templateUrl: './menu.component.html',
      styleUrls: ['./menu.component.scss']
    })
    export class MenuComponent implements OnInit {
      list:any = [
        {val: 1, checked: false},
        {val: 2, checked: false},
        {val: 3, checked: false},
        {val: 4, checked: false},
        {val: 4, checked: false}
      ];
      constructor() { }
    
      ngOnInit() {
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 2021-11-11
      • 2013-02-21
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多