Looking to generate an array of objects for showcasing unique components with varying values?

Trying to figure out how to properly display an array of servers in my HTML using *ngFor. I've been searching online for hours but can't seem to find the solution. It's becoming really frustrating...

1 First Component:

@Component({
  selector: 'app-server',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServerComponent implements OnInit {
  serverId: number;
  serverName: string;
  serverStatus: string;

  constructor(id: number, name: string, status: string) {
    this.serverId = id;
    this.serverName = name;
    this.serverStatus = status;
  }
}  

2 Second Component:

@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
  servers: Object[];
  serverObj: Object;


    constructor() {
        this.servers = [];
        this.serverObj = new ServerComponent(0, "testN", "testS");
      }

  createServer() {
      this.servers.push(this.serverObj);
    }
  }
}

3 Error Message:

Compiled with problems:

ERROR

src/app/app.module.ts:12:5 - error NG6001: The class 'ServerComponent' is listed in the declarations of the NgModule 'AppModule', but is not a directive, a component, or a pipe. Either remove it from the NgModule's declarations, or add an appropriate Angular decorator.

12     ServerComponent,
       ~~~~~~~~~~~~~~~

  src/app/server/server.component.ts:9:14
    9 export class ServerComponent implements OnInit {
                   ~~~~~~~~~~~~~~~
    'ServerComponent' is declared here.


ERROR

src/app/server/server.component.ts:14:15 - error NG2003: No suitable injection token for parameter 'id' of class 'ServerComponent'.
  Consider using the @Inject decorator to specify an injection token.

14   constructor(id: number, name: string, status: string) {
                 ~~

  src/app/server/server.component.ts:14:19
    14   constructor(id: number, name: string, status: string) {
                         ~~~~~~
    This type is not supported as injection token.

Answer №1

Component constructors serve the purpose of dependency injection exclusively. Typically, you do not directly instantiate components using JavaScript; instead, you include their tags in an HTML file.

If you require a class with a standard constructor, it is best to utilize a regular class for that purpose. To pass data between components, there are various methods available depending on your specific scenario.

Based on your situation, it seems like both these components are necessary, requiring another class to manage the data.

export class Server {
  serverId: number;
  serverName: string;
  serverStatus: string;

  constructor(id: number, name: string, status: string) {
    this.serverId = id;
    this.serverName = name;
    this.serverStatus = status;
  }
}  

You can then create an array of servers as you attempted. Normally, the ngOnInit lifecycle hook is used in a component, as the constructor primarily handles DI. This is why components implement the interface by default.

@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
  servers: Server[] = [];

   ngOnInit() {
      this.servers.push(new Server(0, "testN0", "testS0"));
      this.servers.push(new Server(1, "testN1", "testS1"));
      this.servers.push(new Server(2, "testN2", "testS2"));
   }
}

To pass a single server to each ServerComponent, you can achieve this by including an @Input() property.

@Component({
  selector: 'app-server',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServerComponent implements OnInit {
  @Input() server?: Server;

   ngOnInit() {
      console.log(this.server);
   }
}  

You also have the option to provide a default value instead of using a ?.

@Input() enables you to input data into a component via HTML. Moreover, utilizing ngFor* allows you to iterate through the array and generate one component for each entry within the array.

In your servers.component.html

<app-server *ngFor="let server of servers" [server]="server"></app-server>

Square brackets denote an input property.

This will result in creating three instances of ServerComponent once you instantiate a ServersComponent.

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

Developing a system that combines REST API and Socket.io to handle user permissions and send out notifications

Currently, I am working on building a restful API in node.js/express to perform standard CRUD operations. In addition to this, I want to be able to notify clients of any Create/Update/Delete events that occur using either ws or socket.io for simplicity. I ...

Can you explain the distinction between angular-highcharts and highcharts-angular?

Our team has been utilizing both angular-highcharts and highcharts-angular in various projects. It appears that one functions as a directive while the other serves as a wrapper. I'm seeking clarification on the distinctions between the two and recomme ...

Adding a layer to an HTML element causes CSS to malfunction

I am encountering an issue with my HTML code. Initially, it looks like this: <div style=" display: grid; grid-template-columns: 200px 200px 200px;"> <button style="width:100%; height:100%" *ngFor="let valu ...

Obtaining downloaded content data from the root element in Angular2: A step-by-step guide

Despite countless hours of searching, I have yet to uncover a solution. I am seeking to incorporate a share function into an article, akin to a WordPress shortcode. Within the content, there are instances of < feature > Feature content < /feature ...

Strange error message regarding ES6 promises that is difficult to interpret

Snippet getToken(authCode: string): Promise<Token> { return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => { if (json["error"]) { return Promise.reject(json); } return new Token ...

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...

The absence of type-safety in the MUI System sx is a glaring issue

I want to ensure that the TypeScript compiler can identify typos in my MUI System sx props: import { Box, SxProps, Theme, Typography } from '@mui/material' const sxRoot: SxProps<Theme> = { width: '100vw', height: '10 ...

Substitute terms with the usage of array map

Here is an array for you (2) ['beginning=beginner', 'leaves=leave'] as well as a string its beginner in the sounds leave that has been converted to an array using the following code var words = text.split(' '); My goal ...

The microservices system fails to initialize

I've recently delved into the world of microservices, but I've hit a roadblock in my application. app.listen(port) Despite adding .catch() I'm still unable to figure out what's going wrong. The function in question looks like this: nx ...

The constant value being brought in from an internal npm package cannot be determined

I have developed an internal npm package containing shared types and constants. My project is built using TypeScript with "target": "ESNext" and "module": "NodeNext". Within one of my files, I define: export type Su ...

Combine various objects into an array and ensure that any modifications are coordinated

Recently, I integrated a third-party component called <datetime-picker> into my project. This component requires a Date[] of size 2 as its v-model in order to set a range of time. However, in my existing codebase, I have been using two separate Date ...

Enhancing the appearance of div content in Angular by utilizing local template variables and material elements

Within this particular implementation, I have utilized an md-sidenav component with a local template variable #sidenavsearchArea. <md-sidenav #sidenavSearchArea align="" mode="push" opened="false"> sidenav content here.. </md-siden ...

Tips for showing nested JSON data in a PrimeNG table within Angular version 7

I am struggling to display nested json data in a PrimeNG table. When I retrieve the data using an HTTP service, it appears as [object][object] when displayed directly in the table. What I want is to show the nested json data with keys and values separated ...

Switch the orientation of the content flow in bootstrap columns from horizontal to vertical

I am currently working on a file explorer project and I have run into an issue with the layout. My goal is to create a layout similar to Windows file explorer, where files are displayed vertically. However, my current code is arranging them horizontally li ...

tsc converts modern ES6 code into the older ES5 version

Using TypeScript 2.2, I attempted to compile my ES6 module (js file) with the tsc compiler and it successfully converted it into valid ES5 code. Previously, I relied on tools like Google's Tracur for this task. I was unsure if this capability of compi ...

Every time I attempt to maintain an object's state, TypeScript keeps throwing this error at me

interface Data { petname: string, petprice: string, category: string, pettype: string, gender: string, short: string, details: string } const [petdata, setPetdata] = useState<Data>({}); const [img, setImg] = useSt ...

There seems to be an issue with Firebase authentication on firebase-admin in node.js. Your client is being denied permission to access the URL "system.gserviceaccount.com" from the server

Issue I've been utilizing Firebase auth on my client and using firebase-admin to verify on the server. It was functioning well until I decided to migrate to a different server, which caused it to stop working. The crucial part of the error message i ...

The Ionic serve command fails to recognize and reflect any saved changes, leading to a lack of automatic reloading

Recently, I encountered a strange issue while using my ionic 2 application. Whenever I execute the ionic serve command, it launches the server on localhost and produces the following output: [12:00:45] ionic-app-scripts 0.0.45 [12:00:46] watch started ...

Tips for effectively utilizing a javascript constructor in typescript

I am attempting to incorporate a Javascript library into my Typescript project. Within the JS library, there is a class called pdfjs-dist with a constructor that is used in this manner: findController = new _pdf_find_controller.PDFFindController({ li ...

Ways to properly exit a function

What is the best way to pass the apiKey from the createUser function in User.ts to Test.ts in my specific scenario? User.ts interface User { url: string, name: string, } class User{ async createUser( user: User ):Promise<void> { le ...