Home > Mobile >  change color in two components using a button click
change color in two components using a button click

Time:10-23

so like the title says.I have a button in books component, when it's clicked a div color in books component and another div in navbar component should change it's color.

- this is the books component :

export class BooksComponent implements OnInit {

  status:boolean = true ;
  color:boolean ;

  constructor(private colorService:ShareColorService) { }
  
  changeTheme(){
    this.status = !this.status ;
  } ;

  public send():void{
    this.colorService.updateColor(this.status) ; 
  }

  ngOnInit(): void {
  }

}

this is the service code that passes data value from books to navbar component :

export class ShareColorService {
  
  private notifs = new Subject<boolean>() ;
  
  constructor() { }

  public getColor(): Observable<boolean>{
    return this.notifs.asObservable() ; 
    }

  public updateColor(color: boolean){
    this.notifs.next(color) ;
  }
}

and this is navbar component :

export class NavbarComponent implements OnInit {
  
  public navbarNewColor:boolean ;
  public subscription: Subscription ;
  constructor(private colorService:ShareColorService) { }

  public ngOnDestroy(): void{
    this.subscription.unsubscribe() ;
  }

  public ngOnInit(): void {
    this.subscription = this.colorService.getColor().subscribe(color => this.navbarNewColor = color) ;
  console.log("navbarnewcolor :",this.navbarNewColor) ;
  }  
}

ternary operator that controls the ngclass to change color :

<nav  class="navbar navbar-expand-lg navbar-light" [ngClass]="navbarNewColor ? 'bg-light':'bg-dark'">

CodePudding user response:

Instead of manually assigning the value to the navbarNewColor variable by subscribing, you could use a more reactive approach here:

export class NavbarComponent {
  
  public navbarClass$ = this.colorService.getColor().pipe(
    map(isLightMode => isLightMode ? 'bg-light' : 'bg-dark')
  );

  constructor(private colorService:ShareColorService) { }
}
<nav class="navbar navbar-expand-lg navbar-light" [ngClass]="(navbarClass$ | async)">

This should give you an idea!

CodePudding user response:

Finally I found the answer!

As I was expecting it was obvious. The service method that updates div color by sending the button click value (true or false) was only running once because it was outside of the click button function.

changeTheme(){
    this.status = !this.status;
    this.colorService.updateColor(this.status); 
    console.log(this.status);
}
  • Related