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

Exploring the DynamoDB List Data Type

Currently, I am working on an angular 8 application where I have chosen to store JSON data in a list data type within DynamoDB. Inserting records and querying the table for data has been smooth sailing so far. However, I have run into some challenges when ...

Having trouble implementing the ternary operator (?) in TypeScript within a Next.js project

Trying to implement a ternary operator condition within my onClick event in a Next.js application. However, encountering an error indicating that the condition is not returning any value. Seeking assistance with resolving this issue... https://i.stack.img ...

Error: "Reflect.getMetadata function not found" encountered during execution of Jenkins job

My Jenkins job is responsible for running tests and building an image. However, I am encountering issues with the unit tests within the job. task runTests(type: NpmTask) { dependsOn(tasks['lintTS']) args = ['run', 'test&ap ...

ng-module with tabbed content

I am facing a unique scenario where I have a UserProfileComponent with a tab structure and I want to add tabs from different modules. UserProfileComponent.html <ngb-tabset> <ngb-tab> <app-user-profile-history></app-user-prof ...

What is the best way to make two buttons align next to each other in a stylish and elegant manner

Currently, I am diving into the world of glamorous, a React component styling module. My challenge lies in styling two buttons: Add and Clear. The goal is to have these buttons on the same row with the Clear button positioned on the left and the Add button ...

Scrolling with React Event

I am attempting to create a scrollbar that only appears when I scroll within a particular area using React. I am utilizing debounce and useState in my implementation. The issue: When I reach the end of the scroll, the event continues to repeat indefinitel ...

update icon when a router link becomes active

<div class="menuItem mb-3" *ngFor="let menuItem of menuItems"> <a routerLink="{{menuItem.link}}" routerLinkActive="active"> <img src="{{menuItem.icon}}" alt="{{menuItem.name}}" /> <p class="text-center f-12">{{me ...

What is the best way to access the data being sent to a router link in Angular?

After navigating to the user page using the router sample below, how can I retrieve the details once it reaches the user page? I need to verify in my user.component.ts that the navigation is triggered by this [routerLink]="['user', user.id, &apo ...

Guide to integrating location-based QR code verification

Currently, I am developing an Angular application where I am utilizing an npm package to generate QR codes. One of my main requirements is to incorporate location-based functionality into the QR code system. For instance, if a user is at a specific hotel a ...

Guide to showcasing images dynamically in Angular using .NET Core API and database

I am looking for a way to showcase an image that is stored in the database. Below is the code snippet showing how the image file gets uploaded to the database. public string UploadImage(IFormFile file) { if (file == null) thro ...

Having trouble inserting the current time into Firebase Firestore

Currently, I am looking to use the current time as an input in Firebase Firestore (timestamp). Initially, when using the code snippet below: today: number = Date.now(); everything appeared to function correctly. However, the time was only updated once, s ...

Using Inheritance to Create Custom Event/Callback Handlers in TypeScript

Currently facing an issue with Typescript that I'm stuck on. I have created a named callback Handler class that receives the allowed list of "events"/"handlernames" as a generic: class NamedHandler<H extends { [key: string]: HandlerFunction }> ...

The patchState function is iterated within the NGRX component-store effect

My program is stuck in an infinite loop and I can't figure out why. interface LatestAppointmentsWidgetState { loading: boolean; page: number; pagedData: Paged<Appointment>; } @Injectable() export class LatestAppointmentsWidg ...

Building the Android release version of an Ionic Cordova app using the command `ionic cordova build android –prod –release` may encounter a failure when it

Having an issue with Ionic 3. Whenever I use cordova build android --prod --release, the APK shows a white screen after splash. Alternatively, when using ionic cordova build android --prod --release, I encounter the following error. https://i.stack.imgur. ...

What is the method for sending a Post request using the "content type" value of "application/x-www-form-urlencoded"?

Need to send a request to the oAuth2 authentication server to obtain a token. The request works fine in postman but encountering issues when trying to make the same request from Angular 4. CORS configuration is correct as other requests are functioning p ...

learning how to transfer a value between two different components in React

I have 2 components. First: component.ts @Component({ selector: "ns-app", templateUrl: "app.component.html", }) export class AppComponent implements OnInit { myid: any; myappurl: any; constructor(private router: Router, private auth: ...

Adding or modifying attributes on a component selector in real-time

@Component({ selector: 'ion-col', templateUrl: 'components-field.html' }) export class FieldComponent { @HostBinding('attr.layout') layout = '¯\_(ツ)_/¯'; element: any; constructor() ...

Connecting Angular components to the Document Object Model (DOM)

In previous versions of AngularJS, you could create a directive and link it to an existing controller, allowing you to use the same controller for multiple directives with different templates. angular .module('App') .component('Name', ...

Backend communication functions seamlessly within the service scope, yet encounters obstacles beyond the service boundaries

I'm facing an issue with accessing data from my backend. Although the service successfully retrieves and logs the data, when I try to use that service in a different module, it either shows "undefined" or "Observable". Does anyone have any suggestions ...

Is there a way to view the type signature of the resulting intersection type (type C = A & B) in IDE hints, rather than just seeing the components?

When analyzing types defined by intersection in Typescript, I notice that the hint remains identical to the original definition: https://i.stack.imgur.com/mjvI8.png However, what I actually want is to visualize the resulting shape, similar to this: http ...