Tips for identifying modifications within an array passed to an Angular @Input

I am facing an issue with a table filtering component that contains an input in the form of an array of objects. Upon initialization, all the objects in the array have their property isFiltered: false. However, if I use setTimeout() to display the array after one second, some objects are then shown as isFiltered: true. I attempted to utilize ngOnChanges() to detect these value changes, but Angular did not recognize them.

The service call from the parent component is as follows (we are focusing on this.filters):

      this.supportedTypesService
        .getSupportedPolicyTypes()
        .pipe(
          takeUntil(this.ngOnDestroy$),
          finalize(() => (this.delayGettingPreferencesOnInit = false))
        )
        .subscribe((response: PolicyType[]) => {
          this.filters = response.map((policyType: PolicyType) => {
            return {
              value: policyType,
              text: PolicyType.getApiValue(policyType),
              isChecked: false
            };
          });
        });

this.filters is passed down to the child component in the HTML as [filters]=filters

The child component code includes:

@Input filters: Filter[]

  public ngOnChanges(): void {
    each(this.filters, (f: Filter) => {
      if (f.isChecked) {
        this.isFiltered = true;
        return false; // to break from forEach loop
      }
    });
  }

Despite using ngOnChanges(), it does not recognize changes in the array. I also attempted ngDoCheck(), but it resulted in running infinitely, raising concerns about performance issues.

Answer №1

Looking at the code provided for the parent component, it appears that isChecked is set to false for every filter entry. This suggests that there may be updates to the content of this.filter happening elsewhere as well.

When modifying the content of this.filter in the parent component, do you create a new reference for it? For example, this.filter = {...this.filter};

Angular is unable to detect changes within an array directly. The variable this.filters essentially points to a specific memory location. When you modify elements within the array, the memory location remains the same but the actual content within that memory changes. To ensure that the child component recognizes these changes, you need to create a new reference.

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

Using eslint with the vue plugin allows you to specify which object fields to ignore in

My ESLint rule setup includes the following: "vue/script-indent": [ "error", 4, { "baseIndent": 1, "switchCase": 1, "ignores": [ "[init.type=\"ObjectExpression\"]", "[init.type= ...

Extract token from the URL and then use Axios in Vue.js to send it to the POST API

Hey there, I'm in need of extracting a token from the URL http://192.168.178.25:8080/register?token=eyJhbGciOiJIUzI... and then making a POST request to the API to confirm the account. I've attempted this but encountered a SyntaxError on the ...

c# Best practices for populating an array with Json data

I have come across various libraries that can parse Json data, but unfortunately, I haven't found any documentation on how to efficiently get the data into a C# array or list. Here is an example of the Json data I am working with: {"001":{"Name":"Jo ...

Output certain elements from an array and then incorporate them into an if-else statement

I am currently working on developing an on and off switch that is based on an item within an array. The data has already been extracted from JSON, so now I just need to work with the array. This array has been generated from an API call and is returned in ...

Mastering the art of shaping state in NGRX for the master-detail pattern

Imagine a scenario where I am developing a compact app for organizing tasks. This app makes use of angular and NGRX to efficiently manage the state. Each day, the user loads tasks in the morning and then travels to different locations to complete them. Th ...

retrieving tunes from minitune

I am trying to retrieve a list of songs using the tinysong API, which pulls data from Grooveshark. I am making the request through $.ajax and here is what I have so far: $.ajax({ url : 'http://tinysong.com/s/Beethoven?format=json&key=&apos ...

How can I dynamically remove the sticky class when scrolling down in an Angular 6 application?

My Angular 6 app has a simple navbar with ng-sticky for a sticky effect on desktop, but I don't want the navbar to be sticky on mobile devices. Here is the HTML code: <div class="main-header"> <nav class="main-nav" ng-sticky [offSet]="0" ...

I am wondering if it is feasible for a POST route to invoke another POST route and retrieve the response ('res') from the second POST in Express using Node.js

Currently, I have a POST route that triggers a function: router.route('/generateSeed').post(function(req,res){ generate_seed(res) }); UPDATE: Here is the genrate_seed() function function generate_seed(res) { var new_seed = lightwallet. ...

"Discover the process of utilizing jQuery to trigger an action when scrolling past a

I'm currently working with this code snippet: #main { max-width: 500px; height: 900px; margin: auto; background: green } .menu1 { height: 30px; background: red } .menu2 { display: none; } <div id="main"> <div class="menu1"& ...

NestJS: Specify the data type for @Body()

Consider the code snippet below: @Post() public async createPet(@Body() petDetails: PostPetDto): Promise<any> { } In this scenario, the type of @Bod() petDetails defaults to plain/any instead of the declared type of PostPetDto. What is the recommen ...

Deleting data using Angular's HttpClient

When attempting to remove data from my database using an HttpClient in Angular, I am utilizing a service (MemberService) that includes a method called delete. Here is the code for my MemberService: export class MemberService { constructor(private http: ...

Tips for creating a responsive Youtube embedded video

Check out this website for a good example: If you take a look, you'll notice that the header youtube video is responsive - it automatically resizes when the window size changes. Here are the <iframe> codes: <iframe id="bluetube-player-1" fr ...

What is the best way to ensure that my program runs nonstop?

Is there a way to have my program continuously run? I want it to start over again after completing a process with a 2-second delay. Check out my code snippet below: $(document).ready(function () { var colorBlocks = [ 'skip', 'yell ...

Can anyone recommend an easy regular expression to validate date format patterns?

While searching for regex patterns to validate date values in a specific format, I came across numerous options. However, I prefer to allow users to input their own custom date patterns such as: d-mm-yyyy MM/dd/yy yyyy.mm.d I am looking for a ...

What is the best way to implement a Semantic UI radio group in a React component using the State Hook?

I've been attempting to create a radio button group using Semantic UI within React. While I was able to successfully implement the Radio Group example from the Radio page by extending Component, I encountered challenges when trying to rewrite it using ...

What is the best way to store multiple parameters as a single parent parameter in jQuery?

Here is the current code snippet: $(this.form).attr("action",$(this.form).attr("action") + '?' + $("#sortable").sortable('serialize') + "&foo[]=bar"); This code generates the following output: importance[]=1&importance[]=2&am ...

The jQuery click function triggers immediately upon the loading of the page

Despite my best efforts to resolve this issue independently and conduct extensive research on Google, I am still unable to identify the root of the problem. It seems that the click function continues to activate upon page load. Kindly elucidate the under ...

Challenges with compiling TypeScript in Angular2 Form components

In Angular2, I have created a form with the following structure: this.form = this._formBuilder.group({ password: ['',Validators.required], passwordRepeat: ['',Validators.required] }); The form is defined as: p ...

How can we improve the Promise.all syntax for cleaner code?

Recently diving into Node.JS, I find the syntax of Promise.all returning an array to be quite frustrating. For example: const requiredData = await Promise.all([ getFirst(city), getSecond(hubIds), getThird(city, customerCategoryKey ...

Is there a method to track the number of active onSnapshot listeners from Firestore in my application?

In my app, I am implementing a feature that dynamically removes query onSnapshot listeners and replaces them with new ones. To ensure that resources are properly freed up, I need to test the effectiveness of the unsubscribe function. Unfortunately, I do n ...