角材料垫-按钮-切换组默认值未设置为undefined

时间:2020-04-14 06:53:48

标签: angular angular-material

我需要用于搜索的三种状态的组件,默认值为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

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

检查以下内容: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作为值。您可以使用任何其他数字或值。

答案 1 :(得分:0)

您已经注意到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}}
相关问题