Home > Back-end >  Angular - How to only show/be able to click the next screen button after making several selections
Angular - How to only show/be able to click the next screen button after making several selections

Time:04-22

I have a screen where a user can make a selection of different options out of a table of several, but they have to at least choose 3 before they can move on but I'm completely lost on how to implement this or really what to search for to research it.

So far I have a Array of Values in my component:

values = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6","Option 7","Option 8","Option 9", "Option 10","Option 11","Option 12",]

(Note: these will be changed to a API call later, but for now fake data is fine)

and these display on screen and can be selected and deselected fine, however I now want to only limit this to 3 selections and enable the next button on 3 selections

Current Code on the Selection buttons

<div *ngFor="let value of values">
    <button class= "selection_btn text-center" #btn (click)="btn.classList.toggle('selected')">{{value}}</button>
  </div>

Next Button:

 next(){
    this.router.navigate([`${appRoutesNames.PAGE_2}`]).then();
  }

Please note that the Route Name is different in my file, this is just a placeholder

CodePudding user response:

That's the purpose of form controls.

You can hack it a bit to suit your needs :


control = new FormControl([], [
  Validators.minLength(3), 
  Validators.maxLength(3), 
  Validators.required
])


<button 
  #btn 
  class= "selection_btn text-center"
  (click)="control.setValue(control.value.concat([value]))"
>{{value}}</button>

You can then check for the condition

<button [disabled]="!control.valid" [routerLink]="['page2']">Next page</button>
  • Related