Exploring the World of Angular: Abstracts and Data Transformations

Facing a perplexing issue with a component that is based on an abstract class, or at least that's my assumption.

There are multiple sibling components rendered using *ngFor based on an array length. These siblings, derived from an abstract class, receive their data through @Input properties, process it individually, and display it. Everything seemed to be working fine until I noticed a strange behavior where hovering over one of the components caused the data to dynamically mutate (for lack of a better term) and reset to the data of the last sibling within that template.

<Router-outlet>
  <ParentComponent>
    *ngFor
    <Sibling1>
      <ChildComponentA>
      <ChildComponentB>
    <Sibling2>
      <ChildComponentA>
      <ChildComponentB>
    <SiblingN>
      <ChildComponentA>
      <ChildComponentB>

I've thoroughly checked all possible lines of code with breakpoints, and everything seems to be set up correctly. However, whenever I hover over the component, it appears that the change detection activates and fetches the data from the last sibling, overwriting the data for every other sibling in the template. This issue doesn't seem to affect the children of the siblings, as they still display the correct data. But the template of the hovered sibling component gets corrupted. I'm at a loss here. I've tried using [...array] and array.slice() to ensure unique arrays but haven't found a solution yet.

Provided below is a simplified sample code snippet:

parent.component.html

<ng-container *ngIf="v === 'user'">
    <div *ngFor="let e of employees">

        <div>
            <h3>{{ e | name }}</h3>
        </div>
        
        <ng-container *ngTemplateOutlet="days; context: { e: e }"></ng-container>

    </div>
</ng-container>

<ng-template #days let-l="l" let-e="e">
    <div>
        <sibling
            [weeks]="weeks"
            [viewMode]="v"
            [loc]="l"
            [emp]="e"
            [realDates]="realDates"></sibling>
    </div>
</ng-template>

And here is the sibling.component.html

    <div *ngFor="let day of selectedWeek;">
        <div>
            <i *ngIf="viewMode == 'location'"
                class="ico"
                [ngClass]="{
                    'i-x-o': !day.isOpenOnDay && day.isSpecialDay,
                    'i-day-time': day.isOpenOnDay,
                    'is-special': day.isSpecialDay
                }"></i>
            <childA></childA>
        </div>

        <div>
            <childB [day]="day"></childB>
        </div>

    </div>

<childB> maintains stability and accurately displays the data for day. However, hovering over childA, childB, or even the <i> element with icon classes results in the utilization of the day object from the last sibling. The selectedWeek property in the sibling component is sourced from the input weeks, then processed, sliced, and manipulated accordingly.

  • parentComponent: ChangeDetectionStrategy.Default
  • sibling: ChangeDetectionStrategy.OnPush
  • childA: ChangeDetectionStrategy.Default
  • childB: ChangeDetectionStrategy.OnPush

Answer №1

Just an update for those interested: what ultimately solved the issue was transforming the variable selectedWeek into a function. Following that adjustment, everything fell into place as intended. Here's how it looks in sibling.component.html:

<div *ngFor="let day of selectedWeek()">
    <div>
        <i *ngIf="viewMode == 'location'"
            class="ico"
            [ngClass]="{
                'i-x-o': !day.isOpenOnDay && day.isSpecialDay,
                'i-day-time': day.isOpenOnDay,
                'is-special': day.isSpecialDay
            }"></i>
        <childA></childA>
    </div>

    <div>
        <childB [day]="day"></childB>
    </div>

</div>

and then in the sibling.component.ts

public function selectedWeek(): Array<any> {
  // do stuff, return an array
}

I'm still puzzled as to why using a variable didn't work initially.

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

Updating the DOM after making changes with Maquette involves calling the `renderMaquette

In a previous discussion, I expressed my desire to utilize Maquette as a foundational hyperscript language. Consequently, avoiding the use of maquette.projector is essential for me. However, despite successfully appending SVG objects created with Maquette ...

What is the reason for the inclusion of information in the error log by the `ng

After initiating a production build with the command ng build --configuration production, Angular logs some information to the error log: - Generating browser application bundles (phase: setup)... ✔ Browser application bundle generation complete. ✔ Bro ...

"Transform the appearance of the datepicker input field with Material 15's dynamic

I am in need of assistance to change the color to white for the input date and add an underline to a datepicker element <mat-form-field class="date-criteria-select " [floatLabel]="'always'"> <mat-label class=" ...

What causes the select dropdown to display an empty default in Angular 8 following an HTTP request?

I have created a simple HTML code to populate array elements in a dropdown list, with the default value being fetched from an HTTP service during the ngOnInit lifecycle hook. However, I am encountering an issue where the default value is displayed as empty ...

Incorporate an HTML code string into an Angular 2 template

I am working with HTML code stored in a Component variable, shown below: import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `Hi <div [innerHTML]="name"></div>`, styleUrls: [' ...

Using Typescript alongside Angular 1.6 and browserify for your development needs

Currently navigating the world of working with Angular types in TypeScript and bundling code using Browserify. After following a TypeScript guide related to Gulp, I utilized npm to install the Angular types and put together this simple ts file. import * a ...

Is bundling a Node.js backend a wise decision or a mistake?

Just a thought that crossed my mind - I understand the advantages of bundling client-side code, but what about bundling server-side code with Browserify/Webpack? Is this considered a best practice? ...

What is causing the issue with TypeScript's React.createRef() and its compatibility with the material-ui Button element?

Running on React version 16.13.1, my component class includes a Material-UI Button component and a RefObject to access the button element. class Search extends React.Component<any, any>{ constructor(props: any) { super(props) this.streetV ...

Guide on converting a JSON object into a TypeScript Object

I'm currently having issues converting my JSON Object into a TypeScript class with matching attributes. Can someone help me identify what I'm doing wrong? Employee Class export class Employee{ firstname: string; lastname: string; bi ...

VIDEOJS ERROR: A peculiar mistake has occurred. TypeError: The property 'value' cannot be read since it is undefined in the context of

Recently, I came across a fascinating plugin called videojs-thumbnails for video.js, and I'm eager to incorporate it into my angular component. However, I keep encountering an error that says: VIDEOJS: ERROR: TypeError: Cannot read property 'val ...

What is the best way to define an event binding statement in the Angular code rather than within the template?

Is it possible to define the event binding statement directly in the code (rather than in the template)? I am trying to dynamically create a menu, and while I can achieve this with routes (since they are strings), using event names seems to be more challe ...

strophe js is designed to handle the reception of individual messages specifically within the context of Angular

I am currently utilizing Strophe.js for establishing a connection with an XMPP server in an Angular 4 application. When using the connection.addHandler() method, I can successfully receive a single message within my listener function after the connection h ...

Is it possible to control Firestore's data using an Angular service?

I am currently developing a basic example (Tour of Heroes) in Angular.io utilizing Firestore. In order to enhance readability and organization, the sections related to Firestore were segregated within the service and then referred in each component. Howev ...

typescript function intersection types

Encountering challenges with TypeScript, I came across the following simple example: type g = 1 & 2 // never type h = ((x: 1) => 0) & ((x: 2) => 0) // why h not never type i = ((x: 1 & 2) => 0)// why x not never The puzzling part is w ...

Tips for preventing keyboard events from being inherited by all pages in the stack in Ionic framework

In my Ionic 3 app, I have a specific page called Page1 that requires customized keyboard handling. Here is how I implemented it on Page1: @Component({ ... host: { '(document:keydown)': 'handleKeyboardEvents($event)' } }) expo ...

What is the methodology behind incorporating enumerations in typescript?

I've been curious about how typescript compiles an enumeration into JavaScript code. To explore this, I decided to create the following example: enum Numbers { ONE, TWO, THREE } Upon compilation, it transformed into this: "use strict ...

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...

A guide on utilizing NgFor for a standalone element

I am working with a component that interacts with a service to make REST calls. The code for the API service looks like this: api.service import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; i ...

How Angular Router deals with "/" in a route parameter

I've been working on an Angular project with routing, focusing on a route structure like the one below. { path : 'preview/:Id', loadChildren : () => import('./path/preview/preview.module').then( m => m.Preview ...

Encountered an error trying to access '0' property of an undefined object when iterating through data in angular framework

My API is returning data in the format shown below: "fileName": "data.txt", "onlyInFile1": [ { "_id": "60618e87c2077428e4fedde5", "TERMINAL_ID": "Y6152114", "EXTERNAL_STAN": & ...