I have a simple app that contains 3 things:
I have a random number between 1 and 20 that is displayed indefinitely (interval)
2 up and down buttons that allow me to update the number after each advanced click on 1 or -1
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 >
<pre >{{ this.floor | async }}</pre>
</div>
CodePudding user response:
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.
CodePudding user response:
I think the problem is, that the disabled property gets triggered only once. Try to bind the [disabled] property to a variable and update it on every click. Then reassign the variable on every click by the breakdown function. Something like:
Pseudocode:
component.ts:
upDisabled: boolean;
up(){
this.upDisabled = this.breakDown();
}
component.html:
<input type="button" value="Up" (click)="up()" [disabled]="upDisabled" />
Of course you can do the other stuff in these functions too.
Edit: Please look at @Havald's answer on this question: "@NadavPall Have a look at this Stackblitz. In your example you return true to disable the buttons if the value is <= 20 so it gets disabled on the first click."