mercredi 10 juillet 2019

How to validate angular material checkboxes the angular way?

I have three checkboxes and one input. Additionally I have one formsArray and one formGroup. I would like to validate the checkboxes so that:

  1. Only one checkbox can be checked at a time.
  2. The input is disabled once that checkbox has been checked.
  3. The two other checkboxes are disabled while one is checked.

Now I have worked with angular before. But the reactive forms module is very difficult to master, such that small features like this one are so difficult to figure out - the angular way.

I have tried to get the formsArray values from valueChanges and pass it down to a custom method that checks that there is one true value in that array then locks the input. But this is messy and non angular.

I would like to be able to call

    formGroup.get('checkBoxValues').valid 

on my input, do things the - angular way.

      searchForm: FormGroup;
      artist: FormControl = new FormControl({value: false, disabled: 
     false});
      track = new FormControl({value: false, disabled: false});
      album = new FormControl({value: false, disabled: false});
      searchInput: FormControl;
      formArray: FormArray;
      lockInput: boolean = true; 


     constructor(private searchService: SearchService, private _fb: 
    FormBuilder) {

        this.formArray = new FormArray([
          this.artist,
          this.track,
          this.album
        ]);

        this.searchForm = _fb.group({
          checkboxValues: this.formArray,
          searchInput: null
        });

      }

      ngOnInit() {

 (<FormArray>this.searchForm.get('checkboxValues')).valueChanges.subscr ibe(
      res => this.validateCheckboxes(res)
    );



 validateCheckboxes(controls) : void {
    const lock = controls.find(el => {
      return !el;
    });

    return this.lockInput = lock;
  }


  <mat-checkbox class="example-margin" [formControl]="artist">Artist</mat-checkbox>
  <mat-checkbox class="example-margin" [formControl]="album">Album</mat-checkbox>
  <mat-checkbox class="example-margin"  [formControl]="track">Track</mat-checkbox>

  <mat-form-field class="example-full-width">
    <input matInput placeholder="Type album, artist or track..." type="text" [disabled]="lockInput" [matAutocomplete]="auto">
    </mat-form-field>

Input should be disabled until one checkbox is checked. Once one is checked input should enable. If unchecked again it input should disable again, small but rich feature.

I want to harness the power of the reactive forms module and keep things tight.

Please help!




Aucun commentaire:

Enregistrer un commentaire