Ways to refresh ngOnInit in order to renew Interpolation

Is there a way to trigger a reset of ngOnInit() upon changing a variable?

I am trying to reset ngOnInit() when the theme variable changes. Here is my code:

Settings.ts

export class SettingsPage implements OnInit{
  phraseColor: string;
  ngOnInit() {
    let tch : {} = {'#3f51b5': 'Blue', '#ff9800': 'Orange'}
    let ColorName =  tch[this.settingsService.theme]; /* here is the issue */
    this.phraseColor = ColorName;
  }
  changeTheme(){
    this.settingsService.theme = '#ff9800';
  }
}

Settings.html

<div>Theme is {{ phraseColor }}</div>
<button (click)="changeTheme()">Change language</button>

I am experiencing an issue with the phraseColor variable.

The default value of phraseColor is Blue

When I change the theme variable using changeTheme(), I expect the value of phraseColor to be Orange

However, the value of phraseColor remains Blue

Interestingly, when I navigate away from the page and return, the value of phraseColor is indeed Orange

My question is: how can I force a restart of ngOnInit to update the interpolation?

The theme variable is located in SettingsService.ts

export class SettingsService {
  theme: string = '#3f51b5';
}

Answer №1

ngOnInit is a lifecycle hook that is triggered by the framework and should not be manually called. It is recommended to refactor the class to eliminate this requirement.

Since the value of settingsService.theme is only changed through changeTheme, updates can be made there:

  ngOnInit() {
    this.updateColor();
  }

  changeTheme(){
    this.settingsService.theme = '#ff9800';
    this.updateColor();
  }

  updateColor() {
    let colorMap = {'#3f51b5': 'Blue', '#ff9800': 'Orange'}
    let colorName = colorMap[this.settingsService.theme];
    this.phraseColor = colorName;
  }

If there is a possibility of settingsService.theme being changed elsewhere, the service should use RxJS observable/subject to notify subscribers:

export class SettingsService {
  theme: Subject = new BehaviorSubject('#3f51b5'); 
}

Component can subscribe to the theme changes:

  themeSubscription: Subscription;

  ngOnInit() {
    this.themeSubscription = this.settingsService.theme.subscribe(theme => {
      let colorMap = {'#3f51b5': 'Blue', '#ff9800': 'Orange'}
      let colorName = colorMap[theme];
      this.phraseColor = colorName;
    });
  }

  ngOnDestroy() {
    this.themeSubscription.unsubscribe();
  }

  changeTheme(){
    this.settingsService.theme.next('#ff9800');
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for returning a string array?

My query is about how to return a string[]. Currently, TypeScript is throwing an error because each element of the array has a type of ( T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T] ). How can I accept the 'property' arg ...

Utilizing RXJS in Angular to pull information from numerous services within a single component

There are two services, ser1 and ser2. getdata1() { this.http.get<{message:string,Data1:any}>('http://localhost:3000/api/1') .pipe(map((data1)=>{ return Data1.Data1.map(data=>{ return { id: d ...

Encountering issues when passing a string as query parameters

How can I successfully pass a string value along with navigation from one component to another using query parameters? Component1: stringData = "Hello"; this.router.navigate(['component2'], { queryParams: stringData }); Component2: ...

Different ways to showcase a value from the CSS file on the console using console.log

In this guide, you can learn how to create a custom directive in Angular by following this tutorial: Custom Directive Tutorial. The directive should function as intended. Still, I want to see the color value set in the CSS file displayed on the console us ...

Ionic retrieves a filtered array of JSON data

Having difficulty filtering the array to retrieve values where the parent id matches the id that is provided. For instance, if an ID of 1 is sent, it should result in a new array with 3 items. An ID of 4 will return 1 item, and an ID of 5 will also return ...

Revise the classification of an instance variable within a subclass

I am pondering about the topic of inheritance and types for instance variables in typescript. Consider a basic class as shown below: class Person { instanceVariable: Object; age: Number; constructor(instanceVariable: Object, age: Number) { this ...

Integrating meta tags into Angular Universal through subscription

I am facing challenges with dynamically setting meta tags in my Angular application. I am able to set the tags in the ngOnInit method without any issues, but when I try to use a Subscription, the addTag method doesn't work as expected. export class Ap ...

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

Unable to retrieve values using any = {} in TypeScript Angular 8

import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { enableProdMode } from '@angular/core'; enableProdMode(); @Component({ selector: 'app-home', templat ...

Learning to implement forwardRef in MenuItem from Material-UI

Encountering an error when pressing Select due to returning MenuItem in Array.map. Code const MenuItems: React.FC<{ items: number[] }> = (props) => { const { items } = props; return ( <> {items.map((i) => { return ( ...

Exploring the process of linking MatPaginator to a server-sourced datasource within an Angular Material table

In my Angular 5 project, I am utilizing Angular Material table to create a grid. The data is fetched from an HTTP request and stored in a variable named dataSourceNew within the view.ts file. Since dataSourceNew has dynamic content and structure, no interf ...

Disabling the background shadow effect in Angular Material's Accordion

I successfully disabled the background shadow on the Angular Material Accordion in this demonstration by incorporating the following CSS rule: .mat-expansion-panel:not([class*='mat-elevation-z']) { box-shadow: none !important; /* box-shadow: ...

Do I need to be concerned about a bot attack if my form does not submit to a specific endpoint in a single-page application (SPA)?

My latest project involves a form with fields for email and password, but instead of POSTing the data, it simply calls a function upon submission. Although I'm using Angular, I wonder if I should be worried about potential bot attacks. Do you think I ...

What is the process for obtaining an app icon from the store using Angular?

Currently, I am working on an app using ionic, angular, and Cordova. Within this app, there are links to other apps available in the app store. My main query is: Is there a way to retrieve the icons of these apps from the store? I aim to display these ic ...

Exploring the Nested JSON Data Loop with *ngFor in Angular 5/4

Recently I started working with Angular, and I've created a service to iterate over nested JSON data for my list. export const CATEGORIES: Category[] = [ { id: 1, categoryName:'Accessories', subcatName: [ {subcategory: & ...

Using Angular Material to create a data table with a fixed footer and paginator feature

I am facing a challenge with displaying the sum of rows data in the footer section of an Angular Material Table that has fixed footer and header, as well as a paginator. How can I calculate the sum of rows data to show in the footer? https://i.sstatic.net/ ...

Utilizing Ngrx store for Reacting form validation with the integration of asynchronous validation

I'm currently working on an Angular 8 project where I aim to showcase form errors through NgRx store while utilizing reactive forms with a custom asynchronous validator. login.component.ts @Component({ selector: 'auth-login', templateU ...

Using TypeScript to pass a callback function to labelFormatter in the legend of a Highcharts chart

I am currently experimenting with integrating HighCharts into an Angular2 project using TypeScript. My goal is to customize the appearance of the legend text, adding an image next to it. I've found that HighCharts provides a labelFormatter property w ...

What is the best way to track if a checkbox has been selected or not?

Working on a sports list for a mobile app using Ionic. There is a view where the user can select which sports they want to see on the list. <input type="checkbox" ng-model="sport.checked" ng-init="sport.checked=true"> After selecting ...

Interface circular dependency is a phenomenon where two or more interfaces

In my MongoDB setup, I have created an interface that defines a schema using mongoose as an ODM. import mongoose, { model, Schema, Model, Document } from "mongoose"; import { IUser } from "./user"; import { IPost } from "./posts&q ...