首页 > 解决方案 > 如何使用反应式表单模块验证三个复选框?

问题描述

这应该相对容易,不知道为什么我在挣扎。

我有三个复选框,我想确保用户只点击一个。所以验证器应该检查其他两个框是否已被选中,并防止再次选择。它应该确保至少检查一个。

我尝试过使用自定义验证器,但您只能传递一个控件。我需要一些可以检查所有框以进行验证的东西。

<form class="example-section" [formGroup]="queryType">
  <mat-checkbox class="example-margin" [(ngModel)]="artist" formControlName="artist">Artist</mat-checkbox>
  <mat-checkbox class="example-margin" [(ngModel)]="album" formControlName="album">Album</mat-checkbox>
  <mat-checkbox class="example-margin" [(ngModel)]="track" formControlName="track">Track</mat-checkbox>
</form>```

 export class SearchComponent implements OnInit, OnChanges {

  filteredSearchItems: Observable<SearchResult[]>;
  isLoading = false;
  searchForm: FormGroup;
  queryType: FormGroup;
  disabled: boolean = false;
  artist: boolean;
  album: boolean;
  track: boolean;



constructor(private searchService: SearchService, private fb: 
  FormBuilder) {
this.searchForm = this.fb.group({
  searchInput: new FormControl(null)
});
this.queryType = this.fb.group({
 'artist': new FormControl(false,[CustomValidators.validateQuery]),
  'album': new FormControl(false,[CustomValidators.validateQuery]),
  'track': new FormControl(false,[CustomValidators.validateQuery])
});

}

export class CustomValidators {

    static validateQuery(control: FormGroup): { [s: string]: boolean } 
       {//not sure how to pass in all boxes


   for(const con of control.controls) { // somewhere here is the answer
            if(con.value) {
            return { alreadyChecked: true} 
            }
        }

        return null;
    };
}

标签: angularvalidationmaterial-ui

解决方案


有两种可能的解决方案。

1.)您可以使用单选按钮而不是复选框,这样您只能选择这三个选项中的一个。

2.) 如果你真的想使用复选框。你可以像这样实现它。还创建了一个Stackblitz Demo供您参考

<mat-checkbox class="example-margin" 
              formControlName="artist"
              [disabled]="album || track">Artist</mat-checkbox>   // This will be disabled when album or track is already checked

<mat-checkbox class="example-margin" 
              formControlName="album"
              [disabled]="artist || track">Album</mat-checkbox>   // This will be disabled when artist or track is already checked

<mat-checkbox class="example-margin" 
              formControlName="track"
              [disabled]="artist || album">Track</mat-checkbox>   // This will be disabled when artist or album is already checked.

这样,用户只能从这 3 个选项中检查一项。

笔记:

  • 您应该决定是使用模板驱动表单 [(ngModel)] 还是反应式表单模块 (formControlName),因为您无法在输入标签中合并这两者。

推荐阅读