Unable to find solutions for all parameters needed by a CustomComponent within Angular

Whenever I attempt to compile the project for production, an error pops up:

There is a problem resolving all parameters for EmployeeComponent in C:/.../src/app/employee/employee.component.ts: (?, ?, ?).

Oddly enough, when I run the application, everything functions correctly without any errors.

The EmployeeComponent code snippet appears as follows:

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

import { Score } from '../score/score';

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

  name: string;
  employeeId: number;
  totalScore: number;
  scores: Score[] = new Array<Score>();

  public constructor(name: string, employeeId: number, scores: number[]) {
    this.name = name;
    this.employeeId = employeeId;
    this.totalScore = 0;
    for(let i = 0; i < 5; i++) {
      this.scores[i] = new Score(scores[i], i);
      this.totalScore += scores[i];
    }
  }

  ngOnInit() {
  }

  setTotalScore() {
    this.totalScore = 0;
    for(let score of this.scores) {
      this.totalScore += Number(score.value);
    }
  }

}

The EmployeeComponent contains a variable called scores which has a Type of Score, defined as shown below:

export class Score {
   value: number;
   id: number;
   constructor(value: number, id: number) {
       this.value = value;
       this.id = id;
    }
 }

I am creating the employees like this:

import { EmployeeComponent } from './employee/employee.component';

export var mockEmployees: EmployeeComponent[] = [
    new EmployeeComponent("Lorem Ipsum 1", 1, [10, 20, 30, 40, 50]),
    new EmployeeComponent("Lorem Ipsum 2", 2, [11, 21, 31, 41, 51]),
    (add more EmployeeComponent instances as needed)
];

Any advice on why this error is occurring?

Answer №1

Due to EmployeeComponent being an angular Component (including the @component annotation), it is not possible to provide inputs in the constructor as demonstrated. For more clarity on this topic, please refer to this resource. Furthermore, creating components using new is also restricted.

To assign inputs, utilize @Input. Additional information can be found here

Answer №2

To populate your component with data, make use of the @Input decorator:

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

  @Input()
  name: string;
  @Input()
  employeeId: number;
  @Input()
  scoreNumbers: number[]
  totalScore: number;
  scores: Score[] = new Array<Score>();

  public ngOnInit() {
    this.totalScore = 0;
    for(let i = 0; i < 5; i++) {
      this.scores[i] = new Score(this.scoreNumbers[i], i);
      this.totalScore += scores[i];
    }
  }

Next, include the component in a template using the following syntax:

<app-employee [name]="myName" [employeeId]="myEmployeeId" [scoreNumbers]="myScores"></app-employee>

Ensure that the variables myName, myEmployeeId, and myScores hold the desired data to display.

For more information on data flow within Angular components, refer to the official documentation.

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

How to Restrict the Use of Conditional "If" Statements in Another Function in Angular 7

How can I use an IF condition inside a function to only execute once for a specific action and not for another action? I have a function that is called twice, but I want the first "IF" condition inside the function to only be triggered when the add bank b ...

Is there a workaround for utilizing reducer dispatch outside of a React component without relying on the store?

Recently, I implemented a reducer in my project that involves using react, typescript and nextJS. I am wondering if there is a method to trigger the reducer outside of a react component, such as from an API service. While searching for solutions, most re ...

Is it necessary to separate Lodash orderby functions to ensure they function correctly?

For some reason, I'm having trouble sorting my data using lodash in my front-end client code. All the examples I've come across don't involve working with data in an interface, so I can't figure out where I'm going wrong. Let&apo ...

The mapStateToProps function in a Higher Order Component is receiving an OwnProps argument with a property that is not defined

I'm a new user of react-redux trying to connect a higher-order component to the react-redux store. In the mapStateToProps function, I'm using the ownProps argument to filter the state. However, the property I'm trying to use within OwnProps ...

Utilizing Typescript and sinon to mock the functionalities of jsonwebtoken

Looking for help with mocking the function verify in Typescript's jsonwebtoken library. I've installed typescript, jsonwebtoken, sinon, mocha, and chai along with their corresponding types. However, when trying to stub the function, an error occu ...

formik connects props that are lacking certain properties

Trying to figure out a way to simplify the process of declaring all the properties of formik in my Props when using connect(). The error message I keep encountering is: Type '{ entry: Entry; }' is missing the following properties from type &apos ...

Creating a personalized tooltip in Angular for a bubble chart with ApexCharts

I'm currently working on customizing the tooltip for a bubble chart using the ApexCharts library. Here is the link to my project. ...

Launching ngx-modal in Angular2 without the need for a button click

As a newcomer to Angular2, I am seeking guidance on how to trigger an alert Modal in the event of a failed login within my code. While most examples I have come across rely on a button click, I am wondering if it is possible to achieve this based on the st ...

Having trouble retrieving response headers in Angular 5

After sending a post request to a server, I receive a response with two crucial headers for the client: username and access-token. The Chrome debug tool's Network Tab displays the data from the response like this: In addition, I attempt to log the re ...

Provide a boolean value of true or false to indicate whether all delete operations were successfully completed

Currently, I am using Sequelize, GraphQL, and Typescript for my coding. Within my database, I have two tables named RecordInformation and OtherDescription. The RecordInformation table contains a foreign key called "OtherID" which references the OtherDescri ...

Unable to include a header in an Angular 2 HTTP request

Having trouble with the http request headers while using the following code snippet: let authToken = new Headers() authToken.append("Authorization", "xyz"); this.http.get("http://localhost:8081/hello", {headers: authToken}) .subscribe((response) =& ...

What are the consequences of not subscribing to an HttpClient request that returns observables in an Angular application?

Exploring Angular and TypeScript, I am currently delving into the concepts of HttpClient, observables, and subscribe. When I include the following code in a component function: console.log(this.http.get('assets/user.json')); I receive an objec ...

Angular CDKScrollable not triggering events

I'm having trouble making the angular CdkScrollable work when creating my own div: <div class="main-section" id="mainsection" #mainsection CdkScrollable> <div class="content" style="height: 300px; backgr ...

Pass JSON data from Angular service to component

I have encountered a challenge while trying to pass JSON data from my API service to a component without directly subscribing in the component. The issue arises when attempting to access the data outside of the subscription block, as it returns something u ...

Merge two input fields into one to send data to the backend

I have created two input fields, one for selecting a date and the other for entering a time. Before submitting the form to the backend, I need to combine these two inputs into one variable. For example, <input type="text" name="myDate"> and <input ...

Detecting changes in Angular custom form controls when using `mat-select` with the `selectionChange` event

I'm facing an issue with my custom form control that includes a mat-select element I've been attempting to listen for the change event in the parent component However, my onTouchedCallback doesn't seem to be functioning for some reason Wh ...

Creating a custom component in Angular 2 that includes several input fields is a valuable skill to have

I have successfully created a custom component in Angular 2 by implementing the CustomValueAccessor interface. This component, such as the Postcode component, consists of just one input field. <postcode label="Post Code" cssClass="form-control" formCon ...

Ways to modify the color of mat-icon within an input field using Angular 6

Here is the code from my HTML file: <div class="input-field"> <div> <input type="text" id="name" required email/> <label for="name">Email: <mat-icon svgIcon="mail" class="change-color"></mat-icon> &l ...

Exploring Angular 8: Connecting elements to an array filled with objects

My goal is to achieve the following: https://i.sstatic.net/TQeKN.png In my form, I have 2 fields: description and price. When the plus button is clicked, additional input fields (Input 2 and Price 2) are generated dynamically. I want to bind these field ...

Why is it necessary to create a model in Angular?

Although I am relatively new to Angular and my understanding of all its concepts is limited, I am curious about the practical use of models in observables. For example, consider this code segment: getRestaurants = (): Observable<Restaurant[]> => ...