Angular Material 复选框:将真值添加到数组中

huangapple go评论65阅读模式
英文:

Angular Material Checkbox: add true values in an array

问题

I have a problem with Angular Material and checkboxes. I would like to create an array with all checked checkboxes but seems that is harder than I thought.

dialog-settings.html

<h1 mat-dialog-title>Settings</h1>
<div mat-dialog-content>
  <section [formGroup]="dynamColumns">
    <ul>
      <mat-checkbox color="primary" formControlName="name">Name</mat-checkbox>
      <mat-checkbox color="primary" formControlName="surname">Surname</mat-checkbox>
      <mat-checkbox color="primary" formControlName="date">Date</mat-checkbox>
    </ul>
  </section>
</div>
<p>{{ dynamColumns.value | json }}</p>
<div mat-dialog-actions [align]="'end'">
  <button mat-raised-button color="warn" mat-dialog-close>Close</button>
  <button
    style="margin-left: 8px"
    (click)="onSave()"
    mat-raised-button
    color="primary"
  >
    Save
  </button>
</div>

dialog-settings.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
  selector: 'app-dialog-settings',
  templateUrl: './dialog-settings.component.html',
  styleUrls: ['./dialog-settings.component.scss'],
})
export class DialogSettingsComponent implements OnInit {
  columns: any;
  dynamColumns = this._formBuilder.group({
    name: false,
    surname: false,
    date: false,
  });

  constructor(private _formBuilder: FormBuilder) {}

  ngOnInit(): void {
    console.log(this.columns);
  }

  onSave() {
    // if checkbox is checked ---> join columns array
  }
}

I have already tried accessing dynamColumns.value, but I can't figure out how to filter keys and join into an array if the value is true. This is what I get trying a boolean condition on dynamColumns.value:

This comparison appears to be unintentional because the types 'Partial<{ name: boolean | null; surname: boolean | null; date: boolean | null; }>' and 'boolean' have no overlap.

英文:

I have a problem with Angular Material and checkboxes. I would like to create an array with all checked checkboxes but seems that is harder than I tought.
Angular Material 复选框:将真值添加到数组中

dialog-settings.html

&lt;h1 mat-dialog-title&gt;Settings&lt;/h1&gt;
&lt;div mat-dialog-content&gt;
  &lt;section [formGroup]=&quot;dynamColumns&quot;&gt;
    &lt;ul&gt;
      &lt;mat-checkbox color=&quot;primary&quot; formControlName=&quot;nome&quot;&gt;Name&lt;/mat-checkbox&gt;
      &lt;mat-checkbox color=&quot;primary&quot; formControlName=&quot;surname&quot;
        &gt;Surname&lt;/mat-checkbox
      &gt;
      &lt;mat-checkbox color=&quot;primary&quot; formControlName=&quot;date&quot;
        &gt;Date&lt;/mat-checkbox
      &gt;
    &lt;/ul&gt;
  &lt;/section&gt;
&lt;/div&gt;
&lt;p&gt;{{ dynamColumns.value | json }}&lt;/p&gt;
&lt;div mat-dialog-actions [align]=&quot;&#39;end&#39;&quot;&gt;
  &lt;button mat-raised-button color=&quot;warn&quot; mat-dialog-close&gt;Close&lt;/button&gt;
  &lt;button
    style=&quot;margin-left: 8px&quot;
    (click)=&quot;onSave()&quot;
    mat-raised-button
    color=&quot;primary&quot;
  &gt;
    Save
  &lt;/button&gt;
&lt;/div&gt;


dialog-settings.ts

import { Component, OnInit } from &#39;@angular/core&#39;;
import { FormBuilder } from &#39;@angular/forms&#39;;
@Component({
  selector: &#39;app-dialog-settings&#39;,
  templateUrl: &#39;./dialog-settings.component.html&#39;,
  styleUrls: [&#39;./dialog-settings.component.scss&#39;],
})
export class DialogSettingsComponent implements OnInit {
  columns: any;
  dynamColumns = this._formBuilder.group({
    name: false,
    surname: false,
    date: false,
  });

  constructor(private _formBuilder: FormBuilder) {}

  ngOnInit(): void {
    console.log(this.columns);
  }

  onSave() {
    // if checkbox is checked ---&gt; join columns array
  }
}

I have already tried accessing dynamColumns.value but I can't figure out how to filter keys and join into an array if value is true.
This is what I get trying a boolean condition on dynamColumns.value

This comparison appears to be unintentional because the types &#39;Partial&lt;{ name: boolean | null; surname: boolean | null; date: boolean | null; }&gt;&#39; and &#39;boolean&#39; have no overlap.

答案1

得分: 0

问题是什么?

问题是FormGroup上的value是所有表单控件的对象,因此您无法将其与boolean进行比较。您必须将其视为对象进行处理。

文档中提到:

对于已启用的FormGroup,已启用控件的值作为对象,每个组成员都有一个键值对。

解决方案

要获取为true的字段,您可以使用Object.entries()Array.prototype.reduce()函数。由于您没有指定要返回的类型,我将使用{key: string, value: boolean}作为返回类型。

Object.entries()FormGroup值对象转换为键值对数组。

Object.entries()的输出将如下所示:

[ ['name', false], ['surname', true], ['date', false] ]

然后,您可以根据条件将其还原为数组。

这是您的onSave()函数可能看起来的样子。

onSave() {
  const output = Object.entries(this.dynamColumns.value).reduce(
      (acc: {key: string, value: boolean}[], [key, value]) => {
        if (value) {
          acc.push({key, value});
        }
        return acc;
      },
      []
    );
   this._dialogRef.close(output); // <-- 如果您想关闭对话框
}
英文:

What's the problem?

The problem is that value on FormGroup is an object of all the form controls, so you can't compare it against boolean. You have to work with it as object.

It's mentioned in docs
> For an enabled FormGroup, the values of enabled controls as an object
> with a key-value pair for each member of the group.

Solution

To get the fields that are true you could use Object.entries() with Array.prototype.reduce() function. Since you didn't specify the return type you want.
I will use {key: string, value: boolean} as a return type.

Object.entries() will transform the FormGroup value object to array of key-value pairs.

Output of Object.entries() will look like this

[ [&#39;name&#39;, false], [&#39;surname&#39;, true], [&#39;date&#39;, false] ]

You can then reduce it back to array based on the condition.

This is how your onSave() function could look like.

onSave() {
  const output = Object.entries(this.dynamColumns.value).reduce(
      (acc: {key: string, value: boolean}[], [key, value]) =&gt; {
        if (value) {
          acc.push({key, value});
        }
        return acc;
      },
      []
    );
   this._dialogRef.close(output); // &lt;-- In case you want to close the dialog
  }

huangapple
  • 本文由 发表于 2023年5月11日 05:54:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定