Home > Net >  Angular: disable and enable button
Angular: disable and enable button

Time:06-06

I want when the up button is disable by pressing fix it will be enable To make the up disable I have to double click it, The fix button does not work, I do not know how to sync between the 2 buttons, If I press fix I want the count to be reset to 0 and the up button to enable again.

link for my code in stackblitz

My service:

  export class ElevatorService {
  Count = 0;

  constructor() {}

  breakDown() {
    this.Count  ;
    if (this.Count >= 2) return true;
    return false;
  }
}

My component.ts:

export class AppComponent {
  count = 0;
  buttonsDisabled = false;
  constructor(private elevatorService: ElevatorService) {}

  ngOnInit(): void {
    this.count  ;
  }

  up() {
    this.buttonsDisabled = this.elevatorService.breakDown();
  }

  Fix() {
    return (this.count = 0);
  }
}

My component.html:

<input type="button" value="Up" (click)="up()" [disabled]="buttonsDisabled">

<input type="button" value="Fix" (click)="Fix()" >

CodePudding user response:

You aren't using the count member in your component for anything useful at the moment. I would just remove it and use the count in the service to remove confusion.

Fix() {
   this.elevatorService.Count = 0;
}

Mind that just setting this value is probably not the best way to change the state of your service.

You can use a getter that checks the user for it's state:

get buttonsDisabled() {
   return this.elevatorService.Count
};

Here's some minor edits to your code on Stackblitz.

  • Related