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

Angular 如何使用反应式表单模块验证三个复选框?,angular,validation,material-ui,Angular,Validation,Material Ui,这应该是相对容易的,不知道为什么我在挣扎 我有三个复选框,我想确保用户只点击一个。因此,验证器应该检查其他两个框中的任何一个是否已被选中,并防止再次选择。它应该确保至少检查了一个 我尝试过使用自定义验证器,但您只能传入一个控件。我需要一些检查所有框以进行验证的东西 <form class="example-section" [formGroup]="queryType"> <mat-checkbox class="example-margin" [(ngModel)]="a

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

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

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

<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>```


有两种可能的解决方案

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

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

Artist//当已选中唱片集或曲目时,此选项将被禁用
唱片集//当已选中艺术家或曲目时,此选项将被禁用
曲目//当已选中艺术家或相册时,此选项将被禁用。
这样,用户只能从这3个选项中选择一项

注意:

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

@godhar太棒了!幸好它有帮助。介意你投票吗?那将意味着很多。非常感谢:实际上,这是一种naf方式。
 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;
    };
}
<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.