Issue with Angular component inheritance where changes made in the base component are not being

click here to view the example on your browser

base component

import { Component, ChangeDetectorRef, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-base-component',
  template: `<p>
  <b>base</b> component counter: {{ counter }} --
  <b>should have been updated</b>
</p>
<ng-content select="[body]"></ng-content>`,
  styleUrls: ['base.component.css'],
})
export class BaseComponent implements OnInit {
  @Input()
  public counter = 0;
  constructor() {}

  ngOnInit(): void {
    throw new Error('Method not implemented.');
  }
}

inheritance

import { Component, OnInit } from '@angular/core';
import { BaseComponent } from '../base/base.component';

@Component({
  selector: 'app-inherited-component',
  template: `<app-base-component>
  <ng-container body>
    <p><b>inherited</b> component counter: {{ counter }}</p>
  </ng-container>
</app-base-component>`,
  styleUrls: ['inherited.component.css'],
})
export class InheritedComponent extends BaseComponent {
  public ngOnInit(): void {}
}

app component

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<app-inherited-component [counter]="20"></app-inherited-component>`,
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'everyone';
}

Unfortunately, the base counter is currently set at 0 instead of 20. I need it to be updated correctly.

https://i.sstatic.net/fVVNg.png

Answer №1

Within the InheritedComponent, a new <app-base-component> is created inside the View. By using ng-container, you are able to access the counter of the BaseComponent without initializing it first. All that is required is:

<app-base-component [counter]="counter">
  <ng-container body>
    <p><b>inherited</b> component counter: {{ counter }}</p>
  </ng-container>
</app-base-component>

Alternatively, you can also directly access the counter from the inherited component like so:

{{ counter }}

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

Discover the Location and Sign Up for Angular2+ Service

I'm currently using the Google Maps API to retrieve a user's geoLocation data, including latitude and longitude. My goal is to pass this information to a web API service in order to receive JSON output of surrounding addresses. I have implemented ...

Error: Trying to access 'items' property of an undefined variable leads to a TypeError

I am currently working on creating a webpage with Angular 8 that fetches data from a REST API in JSON format by passing the request ID. My goal is to display this data in an HTML table that I have created. However, I encountered the following error: Typ ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

Date input using manual typing format

I've implemented the ng-pick-datetime package for handling date selection and display. By using dateTimeAdapter.setLocale('en-IN') in the constructor, I have successfully changed the date format to DD/MM/YYYY. However, I'm facing an iss ...

Tips for Customizing the Width of Your Material UI Alert Bar

At the moment, I have refrained from using any additional styling or .css files on my webpage. The width of the Alert element currently spans across the entire page. Despite my attempts to specify the width in the code snippet below, no noticeable change ...

Eliminate elements from an array using a specific key for filtering

My Array is called MainArray MainArray=[{ {First Name: "First Name"}, {Last Name: "Contact"}, {Last Name: "Contact"} ] I am trying to trim the key-value pair from this array like this: if (key == 'First Name') { del ...

In Angular 2+, what is the comparable counterpart to Vue's Vuex?

I have experience with Vue's Vuex, but I am currently working on an Angular application. I would like to implement a similar principle where all components are managed from one central location (like a store in Vue). Is there an alternative to Vuex in ...

How to set up an Angular ErrorHandler?

Attempted to register an Angular ErrorHandler in this simplified StackBlitz environment, but it seems that it's not capturing the error thrown within the constructor of the HelloComponent. Any insights on this issue? Your opinions? ...

The 'jsx' property in tsconfig.json being overridden by Next.js and TypeScript

Is there a way to prevent NextJS from changing the 'jsx' property in my tsconfig.json file from 'react' to 'preserve' when running the development server? This is how my tsconfig.json file looks: "compilerOptions": { " ...

Getting the Most Out of .find() in Angular 4

Despite reading various similar questions, I'm still struggling to make the .find() function work in my application. I have a service with the following API: export class VehicleService { private defUrl = 'API'; constructor(private ht ...

Pause until the user selects either the confirm or deny option before proceeding with the next action

As a beginner in Angular, I am seeking help with my code structure. I have three files: WarningComponent (which displays a warning modal using Bootstrap), modalService (responsible for opening modals), and votingComponent. Within the votingComponent, ther ...

Retrieve the value of a property within the same interface

Is there a way to access an interface prop value within the same interface declaration in order to dynamically set types? I am attempting something like this: export type MethodNames = "IsFallmanagerUpdateAllowed" | "UpdateStammFallmanager& ...

The absence of a function implementation right after the declaration within a TypeScript class is a common issue that needs

I received a handwritten array to populate a table for my class, however I am now fetching this array's content from a JSON during the ngOnInit phase and it is not structured in the way I require. Therefore, I am attempting to create a function that ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Enroll a nearby variable "Data" to an Observable belonging to a different Component within an Angular application

Looking to update the HTML view using *ngIf, depending on a local variable that should change based on an observable variable from a shared service. HTML <div class="login-container" *ngIf="!isAuthenticated"> TypeScript code for the same componen ...

What strategies can be employed to create a system for managing multiple permission groups in MongoDB effectively?

Currently, I am tackling a complex project management application which involves the challenge of setting up resource permissions for various user profiles. The task at hand: User scenario Meet John, a user with a standard user profile. John initiates a ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...

Having difficulty constructing a full stack application using Express

I've been struggling to configure a full stack app using create-react-app with Express and TypeScript. My main issue is figuring out how to compile the server files into a build folder. I have separate tsconfig files for the server and create-react-ap ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

Having trouble accessing a custom factory within a directive in Angular using TypeScript

Having some trouble with my injected storageService. When trying to access it in the link function using this.storageService, I'm getting an undefined error. Any assistance on this issue would be greatly appreciated. module App.Directive { import ...