【问题标题】:Getting multiple checkbox value using Angular10使用 Angular 10 获取多个复选框值
【发布时间】:2021-01-23 21:37:03
【问题描述】:

app.component.html

<form #x="ngForm" (ngSubmit)="submit()">
    <div class="form-check form-check-inline">
            <input [(ngModel)]="details.a" #a="ngModel" type="checkbox" value="1">
            <label class="form-check-label" for="inlineCheckbox1">HELLO A</label>
        </div>
    <div class="form-check form-check-inline">
            <input [(ngModel)]="details.b" #b="ngModel" type="checkbox" value="2">
            <label class="form-check-label" for="inlineCheckbox1">HELLO B</label>
        </div>
    <div class="form-check form-check-inline">
            <input [(ngModel)]="details.c" #c="ngModel" type="checkbox" value="3">
            <label class="form-check-label" for="inlineCheckbox1">HELLO C</label>
        </div>

<button [disabled]="!x.valid" >Submit</button>

</form>

App.Component.ts

export class AppComponent implements OnInit {
details:{
    a:boolean,
    b:boolean,
    c:boolean
} = {
    a:null,
    b:null,
    c:null
}
constructor(){
}
submit(){
    console.log(this.details) //to get true or false if checked
 }  

我正在尝试获取复选框的状态和值,如果选中,我需要将值分配给变量

示例:

如果选中 1 和 3 变量 x = 1 + 3 x = 4

【问题讨论】:

    标签: angular typescript forms checkbox angular-reactive-forms


    【解决方案1】:

    这里 Object.keys(details) 将为您提供对象中存在的键的名称作为数组(如 ["a" , "b" , "c"];

    所以我们有了数组,现在我们使用与for循环相同的map函数(i表示索引),x表示数组的第一项,所以第一次运行x将等于“a”( as a 是 Object.keys(details) 的第一个值。现在我们将通过 if(details[x]) 来检查 object 中的第一个键是否包含值,这将与 details["a"] 相同,所以如果值为 true 我们将 i+1 添加到总数中(因为 i 从 0 开始)

     let total = 0
        Object.keys(details).map((x,i)=>{
        if(details[x]){
         total = total + (i+1)
        
        }
        
        })
    

    【讨论】:

    • 谢谢,但我是 Angular 新手,能否具体说明一下
    • 嗨 Faizal 我试过这段代码,但它返回 undefined
    • @FaizalHussain,循环数组使用forEachmapis 转换数组
    【解决方案2】:

    组件:

    export class AppComponent {
      details: Record<'a' | 'b' | 'c', boolean> = {
        a: false,
        b: false,
        c: false
      };
    
      public get xNumber(): number {
        const numbermap = { a: 1, b: 2, c: 3 };
        return Object.entries(this.details)
          // get only the entries with true value
          .filter(([_key, value]) => value)
          // map the keys having true to an array of numbers
          .map(([key]) => numbermap[key])
          // requred for preventing error from reduce if none selected `[].reduce()`
          .concat(0)
          // sum the numbers with reduce
          .reduce((prev = 0, curr) => prev + curr)
      }
    
      submit() {
        console.log(this.xNumber);
      }
    }
    

    模板:

    <form #x="ngForm" (ngSubmit)="submit()">
        <div class="form-check form-check-inline">
            <input
              id="detailsA"
              name="a"
              [(ngModel)]="details.a"
              type="checkbox" />
            <label class="form-check-label" for="detailsA">HELLO A</label>
        </div>
        <div class="form-check form-check-inline">
            <input
              id="detailsB"
              name="b"
              [(ngModel)]="details.b"
              type="checkbox" />
            <label class="form-check-label" for="detailsB">HELLO B</label>
        </div>
        <div class="form-check form-check-inline">
            <input
              id="detailsC"
              name="c"
              [(ngModel)]="details.c"
              type="checkbox" />
            <label class="form-check-label" for="detailsC">HELLO C</label>
        </div>
    
        <button [disabled]="x.invalid" >
        Submit
      </button>
    </form>
    

    This example on Stackblitz

    【讨论】:

    • 怎样才能同时得到真假和值,通过这种方法只能得到值
    • @Casaper,你不必使用[ngModelOptions]在您使用响应式表单时使用(当使用 ngModel 的输入位于 &lt;form [formGroup]="form"&gt; 内时)
    • 如果复选框现在是真还是假,我怎样才能得到,我需要他们两个
    • @Ashwin 详细信息属性 a、b 和 c 实时更新。它们总是以布尔值包含它们的当前状态。看看我做的 stackblitz 例子:stackblitz.com/edit/…
    • @Eliseo 这个问题是用 Forms 提出的,而不是 ReactiveForms。到目前为止,Angular 还没有将 ngModel 表单标记为已弃用或其他任何内容。我个人也更喜欢 ReactiveForms,但我不会告诉 OP 选择什么。
    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2020-06-01
    相关资源
    最近更新 更多