Issues arise when attempting to override attributes within the HTML of a parent component in Angular

Why does overriding an attribute in a child class that extends from another not work as expected?

Here's a made-up scenario to simplify the issue:

Parent class

file: gridbase.component.ts

import { Component, OnInit } from '@angular/core';
import { Product } from '../grid/product';
import { ProductService } from '../grid/productservice';

@Component({
    selector: 'app-grid-base',
    templateUrl: './gridbase.component.html'
})
export class GridBaseComponent implements OnInit {
  public rows: Product[] = [];  

    constructor(public productService: ProductService) { }

    ngOnInit() {
        this.productService.getProducts_1().subscribe(
            response => this.rows = response
        )
    }
}

file: gribase.componen.html

<h1>Grid Base</h1>

<p-table [value]="rows" responsiveLayout="scroll">
    <ng-template pTemplate="header">
        <tr>
            <th>Code</th>
            <th>Name</th>
            <th>Category</th>
            <th>Quantity</th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-row>
        <tr>
            <td>{{row.code}}</td>
            <td>{{row.name}}</td>
            <td>{{row.category}}</td>
            <td>{{row.quantity}}</td>
        </tr>
    </ng-template>
</p-table>

file: product.ts

export interface Product {
    id?:string;
    code?:string;
    name?:string;
    description?:string;
    price?:number;
    quantity?:number;
    inventoryStatus?:string;
    category?:string;
    image?:string;
    rating?:number;
}

file: productservice.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Product } from './product';
@Injectable()
export class ProductService {
    constructor(private http: HttpClient) { }
    getProducts_1(): Observable<Product[]> {
        return this.http.get<Product[]>('assets/products-example-1.json');
    }
    
    
    getProducts_2(): Observable<Product[]> {
        return this.http.get<Product[]>('assets/products-example-2.json');
    }   
}

file: products-example-1.json

     [
        {
            "id": "1",
            "code": "f230fh0g3",
            "name": "Example 1-1",
            "description": "Product Description",
            "image": "bamboo-watch.jpg",
            "price": 65,
            "category": "Accessories",
            &quo...

<p><strong>Child class</strong></p>
<p><strong>file: gridchild.component.ts</strong></p>
<pre><code>import { GridBaseComponent } from './../gridbase/gridbase.component';
import { Component, OnInit } from '@angular/core';
import { ProductService } from '../grid/productservice';
import { Product } from '../grid/product';

@Component({
  selector: 'app-gridchild',
  templateUrl: './gridchild.component.html',
  styleUrls: ['./gridchild.component.css']
})
export class GridChildComponent extends GridBaseComponent implements OnInit {

  override rows: Product[] = [];

  constructor(override productService: ProductService) {
    super(productService);
  }

  override ngOnInit() {
      this.productService.getProducts_2().subscribe(
          response => this.rows = response
      )
  }

}

file: gridchild.component.html

<p>Grid Child works!</p>

<pre>{{rows | json}}</pre>

<app-grid-base></app-grid-base>

The HTML template of gridchild.component.html displays the JSON correctly, but the line below that references the parent component does not show the updated values (it still shows the original values from the parent class). How can I make it display the same values as row 2 at this point

(<pre>{{rows | json}}</pre>)
?

Answer №1

Components do not inherit data as you might think. In TypeScript, inheritance only occurs at compile time and subclasses can override parent behavior, but not vice versa.

If you wish to achieve your desired outcome, consider adding rows as an @Input variable to the component.

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 steps should I take to resolve the No Session error during the authentication process in a Laravel 9/Angular 13 SPA?

My Angular 13 SPA is successfully authenticating to Laravel 9 (Sanctum), as I am able to obtain the CSRF cookie and complete the authentication step. However, when I try to access other protected API endpoints, I am encountering a 'No Session' er ...

Can one designate something as deprecated in TypeScript?

Currently, I am in the process of creating typescript definitions for a JavaScript API that includes a deprecated method. The documentation mentions that the API is solely for compatibility purposes and has no effect: This API has no effect. It has been ...

What potential outcomes arise from independently initiating multiple components simultaneously?

Here is a scenario where I am able to achieve the following: @NgModule({ imports: [BrowserModule], declarations: [AppComponent, BComponent], bootstrap: [AppComponent, BComponent] <---------- here two components }) By doing this, it will ge ...

Transform the subscription into a string

When I use the http method to retrieve a single user, the output logged in the console looks like this: this.usersService.getOneUser().subscribe(data => { console.log(data) }); email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

Implement Angular and RxJS functions sequentially

this.functionalityClient.activateFeature(featureName) .pipe( concatMap( feature => { this.feature = feature; return this.functionalityClient.setStatus(this.feature.id, 'activated'); } ), con ...

Closing ngx-bootstrap modal post unit tests

After enabling the CSS style in the unit tests of my Angular app, I noticed that every time a component displaying a modal from ngx-bootstrap appears, it remains visible in the browser even after the unit tests for that component have completed running. T ...

Utilize a single component across various instances for enhanced efficiency

After thorough research, I couldn't find a solution to my problem despite similar questions being asked. I've developed an angular component for styled radio buttons and need to use it multiple times on different instances. To get a better unde ...

Service in Angular2+ that broadcasts notifications to multiple components and aggregates results for evaluation

My objective is to develop a service that, when invoked, triggers an event and waits for subscribers to return data. Once all subscribers have responded to the event, the component that initiated the service call can proceed with their feedback. I explore ...

The value of "metadata" is not a valid export entry for Next.js

After I installed Next.js 14 with TypeScript, I encountered an error related to my metadata type definition. import type { Metadata } from "next"; export const metadata: Metadata = { title: "next app", description: "next app 1 ...

Customize the element of the root node of a MUI component using the styled()

I am trying to implement the "component" prop with a MUI component (such as ListItem) using the styled() API. However, I am facing an issue where it says that "component" is not a valid prop. Can someone guide me on how to correctly achieve this? I have se ...

Exploring the concept of ngForm and ngModel within template-driven forms in Angular

Hello, I have recently delved into the world of angular and ionic development. I've learned that interpolation and property binding are used to pass data from the class to the template. Interpolation is limited to strings, whereas property binding su ...

Using MUI-X autocomplete with TextField disables the ability to edit cells

When I double-click on a cell, everything works fine. However, after the second click to start editing the textfield, the cell stops editing. I can still choose an option though, so I believe the issue lies somewhere in the textField component, possibly i ...

Struggling to properly interpret and process the latest data being sent from an Angular single page application (SPA

Currently, I am developing a Single Page Application that utilizes Angular 8 on the frontend and Laravel on the backend. The application involves performing CRUD operations, and specifically when dealing with editing functionality, I encounter an issue. Th ...

Type property is necessary for all actions to be identified

My issue seems to be related to the error message "Actions must have a type property". It appears that the problem lies with my RegisterSuccess action, but after searching on SO, I discovered that it could be due to how I am invoking it. I've tried so ...

Develop a TypeScript class in a distinct file

I currently have ag-grid implemented in an Angular project with a CustomFilter. The problem is that the file containing the code for the CustomFilter function is becoming quite large and difficult to manage. I am now looking to move the CustomFilter to a s ...

insert information into a fixed-size array using JavaScript

I am attempting to use array.push within a for loop in my TypeScript code: var rows = [ { id: '1', category: 'Snow', value: 'Jon', cheapSource: '35', cheapPrice: '35', amazonSource ...

Encountering a script error when upgrading to rc4 in Angular 2

After attempting to update my Angular 2 version to 2.0.0.rc.4, I encountered a script error following npm install and npm start. Please see my package.json file below "dependencies": { "@angular/common": "2.0.0-rc.4", "@angular/core": "2.0.0-rc.4", ...

Generating a dynamic table using Angular

My goal is to populate a table dynamically using the code below: teams.component.ts import { Component, OnInit } from '@angular/core'; import { first } from 'rxjs/operators'; import { TeamService } from 'src/app/services/team.ser ...

Password validations are a key feature of reactive forms

Currently, the sign-up button only becomes enabled if the signup form is valid. However, I am facing an issue where the button is getting enabled even when the password and confirm password fields do not match. I suspect there might be a problem with my i ...

The module './login/servcioprueba1.service' is missing the exported member 'prueba'. Kindly add this member to resolve the issue

I am working on an Angular 8 project that involves a service file. To generate the service, I used the command: ng g s servicioprueba1 After generating the service, I imported it into my code as shown below. Included in Block 2 is the line where I impor ...