I just started learning Angular and it seems a bit different to React which was the first JS framework/library I learned.
I watched some courses this week and I thought I should write down some code and see how far it gets me, test what I've learned. You might recognize the app as it's been one of the challenges listed on Frontend Mentor and I've completed this in React so I wanted to give it a go in Angular aswell.
This is what I've done so far. https://i.imgur.com/HbrndxR.png
Atm, I am not fetching data from the API because I don't know how, just yet. However, what I want to do is:
export class ThemeService {
isLightTheme:boolean = true;
changeTheme():void {
this.isLightTheme = !this.isLightTheme;
}
}
What I did was to link up the button in the header to the changeTheme() function
TS
changeTheme():void {
this.themeService.changeTheme();
this.isLightTheme = this.themeService.isLightTheme;
}
HTML
<button (click)="changeTheme()">...</button>
But I am not sure how to listen to changes of this isLightTheme property in the service and apply it to other components that need to know which theme to apply.
The best way to do this is to use BehaviourSubject from the rxjs lib
The code would look like this:
export class ThemeService {
public isLightTheme: BehaviorSubject<boolean> = new BehaviorSubject(true);
changeTheme():void {
this.isLightTheme.next(!this.isLightTheme.getValue());
}
}
Then, in your components, you can subscribe to the value of isLightTheme like this:
themeService.isLightTheme.subscribe(val=>{
//do something with val
});
Q1: You can use localStorage.
to set the value:
localStorage.setItem("isLightTheme",true);
to get the value
this.isLightTheme = localStorage.getItem("isLightTheme");
Q2: You can use HTMLElement to hide the div (I'm assuming that you are assigning an id to the country card divs).
(<HTMLElement>document.getElementById('your-div-id')).<attribute-to-change>= newValue;
Solution 1: The best answer is to use NgRX state management to store this type of information. which can be shared in other parts of the application. Any update in one place can update the whole application at once.
Solution 2:
Use @Input and @Output decorators to share information between components,
you can see an example here https://indepth.dev/posts/1218/lets-implement-a-theme-switch-like-the-angular-material-site