如何使用反应式表单模块验证三个复选框



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

我有三个复选框,我想确保用户单击一个且仅单击一个。因此,验证器应该检查其他两个框中的任何一个是否已选中,并防止另一个选择。它应该确保至少选中一个。

我尝试使用自定义验证器,但您只能传入控件。我需要一些勾选所有验证框的东西。

<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;
    };
}

有 2 种可能的解决方案。

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

2.(如果您确实想使用该复选框。你可以像这样实现它。还创建了一个堆栈闪电战演示供您参考

<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(,因为您无法将这两者合并到输入标签中。

最新更新