Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular: Trying to disable button after amount of clicks

I have a simple app that contains 3 things:

  1. I have a random number between 1 and 20 that is displayed indefinitely (interval)

  2. 2 up and down buttons that allow me to update the number after each advanced click on +1 or -1

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  3. A function (that does not work) that should disable the button after 20 clicks
    (With the breakDown function)

Some of the functions I used in the service and it’s important that it stays there

It is important to note that I only need help in the third part (the first 2 parts work for me)

My stackblitz :

My Service:

export class ElevatorService {

  floor = new BehaviorSubject<number>(1);
  floorNumber: number = -1;
  Count = 0;


  constructor() {
  }

  getRandomNumbers() {
    return interval(1000)
    .pipe(
      map(() => Math.floor(Math.random() * 20) + 1),
      tap(res => this.floorNumber = res));
  }

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

My component.ts:

 export class AppComponent {
  floor = new BehaviorSubject<number>(1);
  Count = 0;

  ngOnInit(): void {
    this.Count++;
    this.elevatorService.getRandomNumbers().subscribe(this.floor);
  }

  constructor(private elevatorService: ElevatorService) {}

  breakDown() {
    const breakDown = this.elevatorService.breakDown();
    return breakDown;
  }

  up() {
    this.floor
      .pipe(
        take(1),
        filter((v) => v < 20),
        map((v) => v + 1)
      )
      .subscribe((v) => this.floor.next(v));
  }

  down() {
    this.floor
      .pipe(
        take(1),
        filter((v) => v > 1),
        map((v) => v - 1)
      )
      .subscribe((v) => this.floor.next(v));
  }

My component.html: The breakDown function is called in the attribute of the disable in the up and down functions

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

<input type="button" value="Down" (click)="down()" [disabled]="breakDown()" />

<div class="elevator">
  <pre class="floor">{{ this.floor | async }}</pre>
</div>

>Solution :

I created a code demo for you that disables the button after 5 click: link to the demo

Please feel free to adapt the code according to your needs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading