Issue with change detection in Angular array authentication

I am currently working with a parent / child relationship consisting of two components: "Properties" - the parent, and "listingsList" - the child.

Below is the parent template:


<div class="row"> 

   <div class="col-9 p-2">
       <listings-list [properties] = "properties"   ></listings-list>
    
     <div *ngIf="properties?.length == 0"  class="card-text bg-white p-1" i18n="@@noResult" >No results found!</div>   

     <div *ngIf="properties?.length! > 0 && totalNumberOfRecords == null"  class="alert alert-warning my-1" role="alert" i18n="@@paginationWarning">Pagination will load shortly!</div>   

     <div *ngIf="properties?.length! > 0" class="btn-group float-right"> 
       <ngb-pagination [collectionSize]="totalNumberOfRecords" [pageSize]="state!.propertiesPerPage" [(page)]="state!.page" (pageChange)="changePage($event)" [maxSize]="5" [rotate]="true" [boundaryLinks]="true"></ngb-pagination>      
     </div>               
   </div>
</div>



Here's the child component:

@Component
({
   selector: "listings-list",
   templateUrl:"listings-list.component.html",
   styleUrls:["listings-list.component.css"]
})
export class PropertiesListComponent {      

   @Output()
   public block:EventEmitter<Property> = new EventEmitter();

   @Output()
   public unBlock:EventEmitter<Property> = new EventEmitter();

   @Input()
   public properties: Property[] = [] ;     

}

When a listing is deleted by the user, the following method is called in the parent component:

public delete(propertyId: number): void {     

       if (propertyId !== undefined) {
           this.model.deleteProperty(propertyId)
               .subscribe( _ => {
                   this.messageService.reportMessage(new Message(`Property ${propertyId} has been successfully deleted.`));

                   var status: boolean = this.propertyStatus == PROPERTY_STATE_ACTIVE ? true : false;
                   var filter = { createdBy: this.authService.user.userName, isActive: status, pageNumber: this.state!.page, pageSize: this.state!.propertiesPerPage };
                   this.model.getPropertyByFilter(JSON.stringify(filter)).subscribe(data => {
                       this.properties = [...data] ;
                   });

                 
               });
       }
   }

The issue I'm facing is that even though the "properties" array has changed, the change is not detected in the child component.

I understand that as long as the array reference is changed, the change should be detected.

In my case, I believe the array reference is indeed changed.

Any insights on what I might be doing incorrectly?

Appreciate any suggestions. Thank you.

Answer №1

In order to manage input property changes, you have the option of using either ngOnChanges or a setter and getter method. Personally, I find setters and getters to be more effective. You can find more information in the official documentation.

@Component
({
   selector: "listings-list",
   templateUrl:"listings-list.component.html",
   styleUrls:["listings-list.component.css"]
})
export class PropertiesListComponent {      

   private _properties: Property[] = [];
   @Output()
   public block:EventEmitter<Property> = new EventEmitter();

   @Output()
   public unBlock:EventEmitter<Property> = new EventEmitter();

   @Input() set properties(value): Property[] {
      this._properties = value;
   } 

   get properties(): Property[] {
      return this._properties;
   }

}

Answer №2

To implement this functionality, utilize the ngOnChanges method. Within your child component-->

@Input() attributes: Attribute[] = [];
_attributes: Attribute[] = [];

ngOnChanges(){
  _attributes = attributes; //Utilize the "_attributes" variable in your child view
}

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

Guide to defining custom variables from various locations within Angular Js

In my Angular 6 project, I have noticed that in the home.component.ts file, there is a variable being declared at the beginning: public hasResults = false; Then in the home.component.html file, there is a section for displaying this variable: <span st ...

The Nestjs ClientMqtt now has the capability to publish both pattern and data to the broker, as opposed to just sending

I am currently utilizing Nestjs for sending data to a Mqtt Broker. However, I am facing an issue where it sends both the pattern and data instead of just the data in this format: { "pattern": "test/test", "data": " ...

Using a memory cache in development with NextJS does not seem to be effective

When exporting my pages for my simple static blog site, everything runs smoothly and quickly. However, in development mode, the generation of posts is sluggish and I'm looking to implement caching to speed up the process. I have set up a file called p ...

Tips for integrating dynamic external components into Angular applications

I have encountered an issue with my Angular application. My goal is to create an Angular application written in TypeScript and built with (aot). The objective is to create a user dashboard with various widgets, each widget being an Angular component. Wh ...

The error message "Type 'IPromise<{}>' is not compatible with type 'IPromise<TemplatesPagingModel>' in typescript version 2.8.0" is displayed

Currently, I am working on an AngularJS framework (version 1.5.8) with the latest TypeScript files (version 2.8.0). However, after updating to the most recent TypeScript version, the code below is not compiling. Implementation of Angular interface: inter ...

Leveraging Angular 9 pipes to transform an array by applying a filter that utilizes a function to return an observable

Looking for a way to filter an array using a function that returns an observable boolean has been a challenge. The goal is to have a pipe that filters values based on a user's permissions, considering that permissions are observable and may not be av ...

There are currently no examples demonstrating how to populate row headers and dynamic columns in the Material table

Currently, I am facing a situation where I need to have rows as headers and dynamic values in columns for a material table. Below is an example: Department Deparment1 Name Jack Vimal Location Chenn ...

The header of the function specifies only one parameter, however the function call necessitates three

Within my Typescript code, I have a function defined as follows: export const func: AWSLambda.APIGatewayProxyHandler = async ( arg ): Promise<AWSLambda.APIGatewayProxyResult> => { During a unit test, when I attempt to call this function like fu ...

Top method for verifying input during keyup or blur events

When it comes to validating user inputs, I often find myself wondering about the best approach to take. In this case, I have created a regex for numbers with decimal points. .ts part checkIsNumber(event) { console.log('event', event.target. ...

What is the best way to trigger a mat-menu to open with just one click, while also automatically closing any other open menus at

I've encountered an issue where if there are multiple menus in the header, opening a menu for the first time works fine. However, if a menu is already open and I try to open another one, it doesn't work as expected. It closes the previously opene ...

What is the best method to publish my npm package so that it can be easily accessed through JSDelivr by users?

I've been working on creating an NPM package in TypeScript for educational purposes. I have set up my parcel configuration to export both an ESM build and a CJS build. After publishing it on npm, I have successfully installed and used it in both ESM-m ...

When calling a function within a for loop, the function receives the final value instead of iterating through the sequence

I need assistance with setting unique names for objects in an array. I have the following setup: this.array = [{name: null}, {name: null}, {name: null}] Along with a list of reserved names: this.reserved = ["name2", "name3"] My goal is to loop through th ...

Having trouble uploading a PNG image (logo) with Cypress

I have been attempting to upload a png file using Cypress and here is what I have tried so far: Cypress.Commands.add('upload_image', (fileName, selector) => { return cy.get(selector).then(subject => { return cy.fixture(fileName, &apo ...

Tips for creating dynamic amd-dependencies in TypeScript

Is there a way to dynamically load a Javascript language bundle file in Typescript based on the current language without using static methods? I want to avoid having to use comments like this for each bundle: /// <amd-dependency path="<path_to_bund ...

Whenever comparing the types 'string[]' and 'DeliveryTypeEnum', this condition will consistently result in 'true' as there is no intersection between the two. This is highlighted by the error code ts(2367)

Hello everyone, I'm a junior developer and could use some assistance if (query.deliveryType && query.deliveryType != DeliveryTypeEnum.EITHER) { search.push({ terms: { "deliveryType.keyword&q ...

Ways to display collapse content and hide it again with a click

Working on my Angular 2 project, I have created collapsible tabs. When a button is clicked, the corresponding tab collapses, and I want it to be hidden if the same button is clicked again. However, the tabs are generated dynamically or through looping: Th ...

Issue with encapsulation in NG Bootstrap

Having an issue with ng-bootstrap (v7.0.0) and Angular (v10) integration. I am struggling to encapsulate Bootstrap within a specific component while using an accordion from ng-bootstrap. The CSS only works when I include @import "~bootstrap/scss/boot ...

We have detected an unexpected synthetic property called @flyInOut. It is important to verify that you have either included BrowserAnimationsModule or NoopAnimationsModule (in Angular 12) to address this issue

Encountered browser console error stating: Error - Unexpected synthetic property @flyInOut found. To resolve, ensure the following: Either import BrowserAnimationsModule or NoopAnimationsModule into your application. https://i.sstatic.net/OPI1p.png Pack ...

Using a function as an argument to handle the onClick event

I have a function that generates a React.ReactElement object. I need to provide this function with another function that will be triggered by an onClick event on a button. This is how I call the main function: this._createInjurySection1Drawer([{innerDra ...

Experience the mesmerizing motion of a D3.js Bar Chart as it ascends from the bottom to the top. Feel free to

Here is the snippet of code I am working with. Please check the link for the output graph demonstration. [Click here to view the output graph demo][1] (The current animation in the output is from top to bottom) I want to animate the bars from Bottom to ...