What is the best way to assign a child component property for use in the parent constructor?

One of the challenges I faced was passing a property from a base component to its children, particularly when the property needed to be used in the base component constructor. I found a solution by utilizing an intermediate service because the tasks I needed to perform in the base component constructor couldn't be done within the ngInit() method.

Initially, I attempted to use a string parameter in the constructor, like

constructor(injector: Injector, holderName: string)
, but encountered issues with this approach.

Are there any simpler alternatives to using an intermediate service for passing properties between components?

Below is an example of my child component setup:


@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  providers: [DataService]
})
export class ChildComponent extends ParentComponent implements OnInit {

  constructor(injector: Injector, childService: DataService) { 
    childService.componentName = 'Child';
    super(injector, childService);    
    console.log('childService ' + childService.componentName)   
  }

  ngOnInit() {
  }

}

And here is my base component:


@Component({
  template: ''
})
export class ParentComponent {

  private componentName: string;

  constructor(injector: Injector, @Optional() parentService: DataService = null) {
    if (parentService !== undefined && parentService !== null) {
      this.componentName = parentService.componentName;
      console.log('parentService ' + parentService.componentName);   
      //Perform important tasks.

    }        
  }
}

@Injectable()
export class DataService {
  componentName: string = null;
}

Thank you,

Answer №1

Take out the @Component class decorator from the ParentComponent class :

export class ParentComponent {

  private componentName: string;
  // perhaps make it public? I'm not sure how you intend to use it
  constructor(injector: Injector, private holderName?: string) {
    if (this.holderName)
    {
      //Do Something important.

    }        
  }
}

Since there is no relevant component inheritance, there is no need to declare it as a component. If you wish to use the unextended form as a component, simply rename it to ComponentBase and have ParentComponent extend that without the holderName, and all the children should also extend base.

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

Animating Angular ng-template on open/close state status

I am looking to add animation when the status of my ng-template changes, but I am unable to find any information about this component... This is the code in my report.component.html <ngb-accordion (click)="arrowRotation(i)" (panelChange)="isOpen($even ...

Angular framework does not trigger the button click event

Currently, I am in the process of creating a web app and working on designing the register page. My experience with Angular is still at a beginner level. The following code snippet is from the resiger.component.ts file: /** * To create a new User ...

The database migration encounters an issue: The module 'typeorm' cannot be located

When I run the following commands: ❯ node --version v16.19.0 ❯ yarn --version 3.5.0 I am attempting to launch this project: https://github.com/felipebelinassi/typescript-graphql-boilerplate However, when I execute: yarn db:migrate which runs the c ...

Encountering Error ENOENT while running Gulp Build Task with SystemJS in Angular 4

UPDATE: 2020.02.13 - It seems like another individual encountered the same issue, but no solution was found. Check out Github for more details. An array of GulpJS errors is emerging when attempting to construct an Angular 4 Web App with SystemJS. The str ...

Here is the revised text: "What is the best way to send a variable to a component and retrieve it within the ng-template using

I've developed a component named "foo" that accepts a data object and displays it within an ng-template as its own variable. The issue arises when the variable inside the ng-template is of type any, lacking proper typing for checking and autocomplete ...

Tips for setting up a mdl-dialog using a declarative approach

I want to incorporate a mdl-dialog into my component following the example provided here: However, when I try to do so, the compiler throws an error stating: Can't bind to 'mdl-dialog-config' since it isn't a known property of ' ...

Removing excess space at the bottom of a gauge chart using Echarts

After trying to implement a gauge chart using Baidu's Echarts, I noticed that the grid properties applied to other charts are working fine, but the bottom space is not being removed in the gauge chart. Even after applying radius(100%), the space at th ...

What is causing my method chain to return a Promise<Promise<boolean?>> when using browser.wait(ExpectedConditions.presenceOf())?

Currently, I am in the process of creating some protractor tests that look like this: import { browser, element, by, ExpectedConditions } from 'protractor'; export class SomePage { private elements: any = {}; navigateToUpdate(name: string) ...

Angular Space-Friendly Table

After attempting to code the sample in Angular, I realized it wasn't what I was looking for. <table> <th >Number</th> <th >Merchant Name</th> ...

What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed. Here is the complete code documentation: <template> <div class="row" ...

Guide: Ensuring the validity of an object retrieved from a database with Nest.js class-validator

When activating a user, I need to ensure that certain optional data in the database is not empty by using class-validator dto. So far, my controller level validations for body, query, and all other aspects have been successful. The DTO file contains vali ...

Can the Node DNS module be incorporated into Angular code?

I am facing a requirement where I must perform a DNS lookup from client-side code built in Angular. Is it feasible to utilize the DNS module from https://nodejs.org/api/dns.html in Angular? ...

Ways to relay messages from `Outlet` to web pages

My Layout.tsx: import { FC, useState } from 'react'; import * as React from 'react'; import { Outlet } from 'react-router-dom'; export const Layout: FC = () => { const [username, setUsername] = useState('John') ...

What is the reason behind CORS errors being triggered by the inclusion of an HTTP Interceptor?

I am currently building an Angular 6 application that communicates with a PHP REST Api. I am running my development environment on localhost, and in order to avoid CORS errors, I had to enable the Access-Control-Allow-Origin: * setting. Lately, I have bee ...

Enhance your workflow with Visual Studio Code by incorporating multiple commands

Embarking on my journey to create my first VSC extension by following this tutorial. Within the "extension.ts" file resides a simple hello world command. My ambition is to introduce another command called git_open_modified_files, however, the tutorial la ...

Developing a structure or definition for a Map

Currently, I have created a type and interface in TypeScript to explicitly define the things variable and the Map constructor call. type Things = Map<string, ThingValue>; interface ThingValue { label: string; count: number; } const things: Thi ...

Including a Script Tag in an Angular 2 Application with a Source Attribute retrieved from a Web API Request

Situation: Within my Angular 2+ application, I am utilizing a web API to retrieve URLs for script tags created by a function called loadScript during the AfterViewInit lifecycle hook. The web API is providing the expected JsonResult data, which I have suc ...

brings fulfillment except for categories

The new satisfies operator in TypeScript 4.9 is incredibly useful for creating narrowly typed values that still align with broader definitions. type WideType = Record<string, number>; const narrowValues = { hello: number, world: number, } sa ...

Error: The module 'AppModule' has encountered an unexpected value 'CalendarComponent'. To resolve this issue, please include a @Pipe/@Directive/@Component annotation

Recently, I started working with Angular 2 and wanted to incorporate the 'schedule' feature from Primeng. To do so, I installed its package and added the calendarComponent in my app.module.ts file as shown below: import { BrowserModule } from &a ...

Issue with resolving symbol JSON in Angular 7 when using JSON.stringify

Let me start off by saying that I am new to Angular 7. Currently, I am in the process of developing an application using Angular 7 with a C# backend. The specific challenge I am facing is the need to serialize an object in my component/service before sendi ...