【问题标题】:angular material mat-button-toggle-group default value not set as undefined角度材料垫按钮切换组默认值未设置为未定义
【发布时间】:2020-04-15 15:42:01
【问题描述】:

我需要具有三种状态的组件进行搜索,默认值为undefined。所以我使用mat-button-toggle-group 但默认值不会影响组件设计。

html:

<mat-button-toggle-group 
[(ngModel)]="myValue" 
[value]="myValue" aria-label="Font Style">
  <mat-button-toggle [value]="1">Bold</mat-button-toggle>
  <mat-button-toggle [value]="undefined">Italic</mat-button-toggle>
  <mat-button-toggle [value]="0">Underline</mat-button-toggle>
</mat-button-toggle-group>
{{'myValue:'+myValue}}

ts:

  myValue:number;

stackblitz

谁能帮帮我?

【问题讨论】:

  • 为什么还要使用 undefined 作为值?您可以将“Italic”选项的值更改为 -1,然后在通过 API 或作为组件输入 (OnChanges) 或在组件 OnInit 中获取数据时在组件代码中进行一次如下比较: this.buttonValue ? this.buttonValue : -1,它会工作得很好。
  • @Semir Deljić 我有一个搜索对象,并将其字段绑定到组件。其中一个具有零/一个值。如您所知,在搜索直到用户未填写值之前,我无法使结果值生效。因此我需要空状态的默认值。我只需要 undefined 来更新 searchObject 并重置所有搜索过滤器。

标签: angular angular-material


【解决方案1】:

您注意到undefined 值被视为字符串。而myValue 类型是number。

<mat-button-toggle-group 
 value="undefined"
 (change)="myValue = $event ? $event.value : undefined"
 aria-label="Font Style">
  <mat-button-toggle [value]="1">Bold</mat-button-toggle>
  <mat-button-toggle value="undefined">Italic</mat-button-toggle>
  <mat-button-toggle [value]="0">Underline</mat-button-toggle>
</mat-button-toggle-group>
{{'myValue:'+myValue}}

【讨论】:

    【解决方案2】:

    检查这个:https://stackblitz.com/edit/angular-yw9zyq-o1glji

    <mat-button-toggle-group name="fontStyle" 
    #group="matButtonToggleGroup" 
    [value]="2" aria-label="Font Style">
      <mat-button-toggle [value]="1">Bold</mat-button-toggle>
      <mat-button-toggle [value]="2">Italic</mat-button-toggle>
      <mat-button-toggle [value]="0">Underline</mat-button-toggle>
    </mat-button-toggle-group>
    {{'myValue:'+group.value}}

    并且不要使用 undefined 作为值。您可以使用任何其他数字或值。

    【讨论】:

    • 假设我有 SearchFilter 对象,其字段类似于 myValue。当我更新SearchFilter 时,所有字段都设置为未定义。因此默认值应该是“未定义”
    • 如果您将值更改为字符串,该示例将不起作用。
    猜你喜欢
    • 1970-01-01
    • 2019-01-30
    • 2020-02-18
    • 1970-01-01
    • 2021-03-21
    • 2019-03-18
    • 2019-05-05
    • 2019-08-01
    • 2018-04-30
    相关资源
    最近更新 更多