0

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()" >

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much for your help, But I want I set every few clicks is disable you did every 1 click @H3AR7B3A7
You're welcome, I updated the Stackblitz. The idea stays the same though.
Thank you, If I want to transfer the fix function to another service and another component and through it connect to the current component it should be a problem?
Being able to share services between components is mostly what makes them useful. So that should not be a problem. That is why you want the state to be in the service. If you don't want to share the service, but rather multiple instances of it, you can just not provide it in root, but to the component itself. (Right now they are providedIn: 'root', but you can also choose to add them to the providers in either the module or component decorators, depending on whether you want to share it in that module or not.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.