Home > Back-end >  Checkbox unchecked button is disabled
Checkbox unchecked button is disabled

Time:10-14

Here in my stackblitz , Once I clicked the checkbox it will disable the other buttons. So I want to happen here is:

if I clicked Checkbox(Sample1) button1 will be enabled. if unchecked button1 is disabled

hoping someone can help me thank you so much in advance!

https://stackblitz.com/edit/angular-service-disable-button-il3rqn?file=src/app/services/button-disable.service.ts

CodePudding user response:

Your approach is correct. If you want your buttons to be initially disabled, use a different initial value for your BehaviorSubject.

And if you only want one button to be affected, then use a different condition for your second button (you might want to rephrase that part of your question; it's not 100% clear what you're trying to achieve).

CodePudding user response:

Always we want to control two or more elements "not relationated" we need two or more variables (or an Array)

So, the fisrt is that our service dispatch an array of booleans

export class ButtonDisableService {

  private _disableButton: BehaviorSubject<boolean[]> = new BehaviorSubject<boolean[]>([]);

  get disableButton(): Observable<boolean[]> {
    return this._disableButton.asObservable();
  }

  //see that we need in toogle indicate the "index"
  toogleDisable(index:number){
    this._disableButton.value[index]=!this._disableButton.value[index]
    this._disableButton.next(this._disableButton.value);
  }
}

Then in button, we use "map" rxjs operator to get only one element of the array

button 1

  ngOnInit() {
    this.disablee = this.buttonDisable.disableButton.pipe(
           map((x:boolean[])=>x[0]));
  }

and button 2 (we check if x.length>0)

  ngOnInit() {
    this.disablee = this.buttonDisable.disableButton.pipe(
           map((x:boolean[])=>x.length>0?x[1]:null));
  }

Finally in master.html

<input type="checkbox" (click)="toogleButtonStatee(0)">sample1
<input type="checkbox" (click)="toogleButtonStatee(1)">sample2 <br><br>

toogleButtonStatee(index:number){
    this.buttonDisable.toogleDisable(index);
}

see stackblitz

  • Related