我怎样才能要求至少选择一个用于 angular material 切换多个选项?

How can I require at least one to be selected for angular material toggle with multiple options?

我希望用户能够 select 多个选项,但如果只有一个选择,我怎样才能防止 select 这个按钮被取消 select?

HTML:

<mat-button-toggle-group (change)="changeOpt($event)" multiple name="fontStyle" aria-label="Font Style">
    <mat-button-toggle value="opt1" [checked]="true">Opt1</mat-button-toggle>
    <mat-button-toggle value="opt2" [checked]="true">Opt2</mat-button-toggle>
    <mat-button-toggle value="opt3" [checked]="true">Opt3</mat-button-toggle>
</mat-button-toggle-group>

TS:

changeOpt(evt: any) {
    if (evt.value.length === 1) {
        // PreventDefault
    }
}

我想通过查看上面的 select 离子总数来防止,但我不能

stackblitz example

您可以在 formGroup 中使用表单验证器 Validators.maxLength 来解决这个问题,例如:

<form [formGroup]="exampleForm">
  <mat-button-toggle-group formControlName="items" (change)="changeOpt($event)" multiple name="fontStyle" aria-label="Font Style">
      <mat-button-toggle value="opt1" [checked]="true">Opt1</mat-button-toggle>
      <mat-button-toggle value="opt2" [checked]="true">Opt2</mat-button-toggle>
      <mat-button-toggle value="opt3" [checked]="true">Opt3</mat-button-toggle>
  </mat-button-toggle-group>
</form>

{{ exampleForm.controls.items.value }}
{{ exampleForm.controls.items.value.length }}

{{ exampleForm.valid }}

import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'button-toggle-appearance-example',
  templateUrl: 'button-toggle-appearance-example.html',
  styleUrls: ['button-toggle-appearance-example.css'],
})
export class ButtonToggleAppearanceExample implements OnInit {
  exampleForm: FormGroup;
  constructor(
    private formBuilder: FormBuilder,
  ) { }
  ngOnInit(): void {
    this.exampleForm = this.formBuilder.group({
      items: [null, Validators.maxLength(1)]
    });
  }
}

我觉得够了。目前,您选择的选项 .valid 中有一个会变为 false。

如果你想要"avoid"没有按钮被选中-不仅给出错误信息-:

您需要了解 data binding。 Angular 支持单向和双向数据绑定。那是:.ts(模型)中的变量显示在 .html(视图)中。 .html 中的输入更改可以更改 .ts

中的变量

因此,我们使用 [(ngModel)] 为 .ts 中的单个变量赋值

<mat-button-toggle-group [(ngModel)]="value" multiple 
     name="fontStyle" aria-label="Font Style">
    <mat-button-toggle value="opt1" (change)="change($event)">Opt1</mat-button-toggle>
    <mat-button-toggle value="opt2" (change)="change($event)">Opt2</mat-button-toggle>
    <mat-button-toggle value="opt3" (change)="change($event)">Opt3</mat-button-toggle>
</mat-button-toggle-group>

函数改变,检查"value"的长度,如果是1,将值存入变量,如果是0,恢复变量

change(evt: any) {
    if (this.value.length === 1)
      this.oldValue = this.value[0];

    if (this.value.length === 0) 
      this.value = [this.oldValue];

  }

参见stackblitz