Home > Enterprise >  Angular: Disable a Button dependent on a If condition
Angular: Disable a Button dependent on a If condition

Time:07-21

At the moment I have if condition where if the API call sees 0 then the button to go to the next page should be disabled, however I am not sure how to do this as you cannot call a method within another method(?) right now I have the following

HTML:

<button type="button"  (click)="next()">Next</button>

TS:

 ngOnInit(): void {
    this.appService.showLoader(true);
    this.coachService.GetCategories().subscribe(res =>
     {
      if (res && res.length === 0){
          this.appService.openSnackBar('You do not have access to this Service');
         //This line is where I thought to call this method to disable the button
          this.next = [disabled];
          } else if (res && res.length === 1) {
            if( res[0].name === 'pageOne'){
               //irrelevent code          }
//Button

nextMindset(){
//route to pageOne
  }

CodePudding user response:

You could create a control variable, for example, disabled.

disabled: boolean = true;

ngOnInit(): void {
  this.appService.showLoader(true);
  this.coachService.GetCategories().subscribe(res => {
    if (res && res.length === 0){
      this.appService.openSnackBar('You do not have access to this Service');
      this.next = [disabled];
      this.disabled = true;
    } else if (res && res.length === 1) {
      this.disabled = false;
      if( res[0].name === 'pageOne'){
        //irrelevent code          
      }
    }
  }
}

next(){
  if (disabled) return;
  //route to pageOne
}

template

<button type="button"
  
  (click)="next()"
  [disabled]="disabled">Next</button>

CodePudding user response:

HTML:

    <button type="button"
            
            (click)="next()"
            [disabled]="resLength"
    >Next</button>

TS:

    resLength = false;

    ngOnInit(): void {
    this.appService.showLoader(true);
    this.coachService.GetCategories().subscribe(res =>
     {

      resLength = !!res.length;

      if (res && res.length === 0){
          this.appService.openSnackBar('You do not have access to this Service');
         //This line is where I thought to call this method to disable the button
          this.next = [disabled];
       } else if (res && res.length === 1) {
            if( res[0].name === 'pageOne'){
               //irrelevent code          }
    
    //Button
    
    nextMindset(){
    //route to pageOne
      }
  • Related