Leveraging ngOnChanges to determine the display of an overlay based on input alterations

Working with TS/Angular on a web application, I made the decision to refactor some code that handles displaying different overlays. Instead of having separate code for each overlay, I consolidated them into one "master overlay" and created a function within it to determine which settings should be used based on the specific variation needed. This function needs to check if any of the 20 variables that dictate whether an overlay should be shown have changed in order to display the correct overlay. To achieve this, I included all 20 variables as inputs in my component and implemented the function in ngOnChanges. While I am aware that using ngOnChanges can be risky due to running during every change detection cycle, I believe in this scenario I can control when it updates, ensuring it only does so when necessary. Do you think I am wrong for utilizing ngOnChanges in this context?

Despite my team advising against using ngOnChanges, I personally find it suitable for this particular situation.

Answer №1

Using ngOnChanges can be risky because it executes during every angular change detection cycle

This is incorrect, only ngDoCheck runs on each cycle.

ngOnChanges only activates when there is a change in an @Input value. It serves the purpose you need and is safe to use!

Answer №2

My suggestion would be to start by removing all the inputs, as tracking and passing 20 inputs can be quite challenging. Instead, I recommend creating a service (or utilizing state management like ngrx) where you can store all the settings in a model object with 20 properties. Within the child component, initialize a subscription to the service's observable, so that whenever any setting changes, you can trigger change detection (assuming you are using onPush strategy). Check out this link for more information.

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

Encountering an issue when utilizing inversifyJS inject with the error message "Reading '_userService' cannot be done as it is undefined."

I'm currently working on implementing a DI system, but it seems like I may be missing some key concepts of Inversify. Do I need to create a "get" method for the "user.controller" and then "bind" it to the routes function? Link to complete code reposi ...

Using Angular - Executing a query only when a URL parameter is present

Can I execute this query only if a URL parameter (paramOne) is present? queryAndSubscribe(){ this._subscription = this._activatedRoute.params.pipe( tap (params => { console.log('params = ', params); }), switchMap ...

What are the steps to retrieve the original source code of an HTML file, specifically in Angular 2 RC4

Is there a way to retrieve the source code that I manually typed in my IDE using JavaScript? Note: I am working with angular2 rc4. I attempted to access it using Reflect.getMetadata, but encountered errors indicating that it is not functioning properly. ...

Protractor syncing with an Angular page following redirection to an Auth0 non-Angular page

My Angular web application utilizes Protractor for end-to-end tests. Recently, I implemented OAuth0 authentication into my app. To disable Angular synchronization before redirecting to the non-Angular OAuth0 page, I use await browser.waitForAngularEnabled( ...

Is the 'case' in a switch statement not treated as a typeguard by Typescript?

Here is a simplified version of the code I am working with: type Todo = { id: string; text: string; }; type Action = | { type: 'DELETE'; payload: string } | { type: 'CREATE'; payload: Todo } function reducer(state: Todo[], ...

The specified property cannot be found in the type 'IntrinsicAttributes & ...'

I'm currently working on adding a custom prop to a custom styled-component: interface Props { image?: string; title?: string; subtitle?: string; background?: string; } export function CardWide({ image, title, subtitle, background }: Props) ...

Unable to send event from JavaScript to Component in Ionic

My goal is to notify a component that a script file has finished loading. My approach involves using the onload event of an element to dispatch an event. A service will then register an event listener for this event, waiting for clients to subscribe to an ...

Custom filtering for a RadListView with a unique search term

Can a filtering function be passed to an Angular Nativescript RadListView that can access the local variable 'searchTerm'? The provided sample seems to suggest using a static search term, but I want to modify it based on user input. Different Ap ...

Splitting the div into two columns

I've encountered various solutions to this issue, but when I integrate an Angular2 component inside the divs, it fails to function properly. Here is my progress so far: https://i.stack.imgur.com/qJ8a9.jpg Code: <div id="container"> <div ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

Getting a specific piece of information from a JSON file

I am encountering an issue with my JSON file collection. When I access it through http://localhost:5000/product/, I can see the contents without any problem. However, when I try to retrieve a specific product using a link like http://localhost:5000/product ...

Angular 2's Conditional Validation: A Comprehensive Guide

Angular 2 offers straightforward validation, which is a great feature. However, the challenge lies in making a required field optional based on another field's selection. Below are the validation rules: this.contractsFilter = this.fb.group({ selec ...

Guide to configuring an Appium-Webdriver.io project for compiling TypeScript files: [ ISSUE @wdio/cli:launcher: No test files detected, program exiting with error ]

I have decided to transition my Appium-Javascript boilerplate project into a typescript project. I am opting for the typed-configuration as it is officially recommended and have followed the steps outlined in the documentation. Here is an overview of the ...

Configuring ordered imports in TSLint

Need help with configuring my TSLint rule ordered-imports. I want the import order to be like this: // React import React from 'react'; import { View } from 'react-native'; // Libs import * as _ from 'lodash'; import * as mo ...

What is the definition of a type that has the potential to encompass any subtree within an object through recursive processes?

Consider the data structure below: const data = { animilia: { chordata: { mammalia: { carnivora: { canidae: { canis: 'lupus', vulpes: 'vulpe' } } } } }, ...

Uncheck all boxes except for the required or disabled boxes in Angular

HTML: <mat-selection-list #selectedColumns [(ngModel)] ="selectedOptions"> <div class= "content-section"> <mat-expansion-panel> <mat-expansion-panel-header> ...

Unlocking the power of the Angular 2 injector at a global level

Is there a way to globally access an instance of the root Angular 2 injector (for example, from the browser console)? In Angular 1, it was done using angular.element(document).injector(). This can be handy during testing and exploration, allowing you to ...

Retrieve information from Angular 2 response

In my code, I am working with 1 component and 1 service. Here is the component element : ... constructor(private requestService : RequestService) { } ngOnInit() { this.a = this.requestService.send_request(urlWebAPI); console.log(this.a); } ... ...

Changing the color of a Chart.js chart in Angular: A step-by-step guide

I've been struggling to change the color of my chart without success. Any assistance on this matter would be greatly appreciated. Despite trying to assign color values to datasets, I am still unable to achieve the desired result. This is a snippet f ...

Enhancing CKEditor functionality with Angular 2 for improved textarea usage

Check out this Plunker example: https://plnkr.co/edit/aUBtpe?p=preview When using CKEditor, the value of the content variable does not update when changes are made to the textarea. It remains the same as the original page.content variable that was obtaine ...