Working with arrays in Angular 4 to include new items

I am struggling with the code below:

export class FormComponent implements OnInit {
  name: string;
  empoloyeeID : number;
  empList: Array<{name: string, empoloyeeID: number}> = []; 
  constructor() {
  }

ngOnInit() {
  }

onEmpCreate(){
   console.log(this.name,this.empoloyeeID);
   this.empList.push.apply(this.name,this.empoloyeeID);
   this.name ="";
   this.empoloyeeID = 0;
   }
}

I encountered an error while running this code:

CreateListFromArrayLike called on non-object

Is there a way to create a custom class and use object list instead of defining an array in this code?

Thank you

Answer №1

Indeed, there is a method to achieve this.

To start, define a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Next, import the class into your component.

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another option would be to utilize interfaces. For more information, refer to the documentation here - https://www.typescriptlang.org/docs/handbook/interfaces.html

Additionally, take a look at this intriguing question - When to use Interface and Model in TypeScript / Angular2

Answer №2

The data type of your empList is object, yet you are attempting to push strings into it

Consider using the following code snippet:

this.empList.push({this.name,this.employeeID});

Answer №3

Add an item to your array by utilizing the following code snippet:

export class FormComponent implements OnInit {
    name: string;
    empoloyeeID : number;
    empList: Array<{name: string, empoloyeeID: number}> = []; 
    constructor() {}
    ngOnInit() {}
    onEmpCreate(){
        console.log(this.name,this.empoloyeeID);
        this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
        this.name = "";
        this.empoloyeeID = 0;
    }
}

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

What steps should I take to resolve an Angular error that occurred following the installation of Font Awesome

After installing font awesome, I encountered this error: Uncaught TypeError: Class constructor Platform cannot be invoked without 'new' at Module../node_modules/@angular/cdk/ivy_ngcc/fesm2015/platform.js (platform.js:78) at webpack_require (boo ...

Tips on narrowing down the type of callback event depending on the specific event name

I've been working on implementing an event emitter, and the code is pretty straightforward. Currently, tsc is flagging the event type in eventHandler as 'ErrorEvent' | 'MessageEvent'. This seems to be causing some confusion, and I ...

Ionic app experiencing a CORS dilemma post-build

Using Ionic 3, I have written a provider code to fetch data from an API endpoint hosted on an HTTPS server. For example, my endpoint is located at . Below is the code for my provider: // Provider Class Function load(){ if(this.data){ return Pro ...

Retrieving the <html> tag within an Angular component

In an Angular component, the <body> and <head> tags can be accessed by injecting DOCUMENT as shown below: import { DOCUMENT } from '@angular/common'; import { Inject } from '@angular/core'; export class TestComponent { c ...

Is it possible to assign a type conditionally depending on the value of a boolean?

While grappling with this issue, the title question arose in my mind: How can I handle the situation where the library function getResponse returns { a: number } for Android phones and { b: number } for iOS phones? The code snippet below initially led to ...

What is the best way to trigger a function in React when a constant value is updated?

In my React application, I have 3 components. The parent component and two child components named EziSchedule and EziTransaction. Each component fetches its own data from an API. The data to display in the EziTransaction child component depends on the reco ...

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

Exploring the Magic of Angular 5 Reactive Forms: Step-by-Step Guide to Dynamically Implement Validators and Displaying Errors upon Form Submission

My goal is to dynamically manage the required validator for form fields. It seems to be working fine when the user interacts with the field before submitting the form, as it validates onBlur and onSubmit. However, if a user submits the form without interac ...

Set the class function to be uninitialized

I'm a little unsure of my TypeScript knowledge. I have a class MyClass with a member variable that is a function, but I don't know what this function will be at compile time. I want to allow external code to set this function dynamically during r ...

No invocation of 'invokeMiddleware' was suggested

Encountered this specific issue when setting up loopback4 authentication. constructor ( // ---- INSERT THIS LINE ------ @inject(AuthenticationBindings.AUTH_ACTION) protected authenticateRequest: AuthenticateFn, ) { super(authen ...

Choosing specific information in Typescript response

I am encountering an issue with my HTML where it displays undefined(undefined). I have checked the data in the debugger and I suspect that there may be an error in how I am using the select data. Here is a snippet of the code: <div *ngIf="publishIt ...

Enhance ngx-bootstrap's tab content with ngx-scrollbar functionality

Currently in my project, I am utilizing bootstrap 4 and ngx-bootstrap. One requirement I have is to develop a component consisting of 2 scrollable divs that can be switched by tabs. I was hoping to demonstrate a sample application on stackblitz, but unfor ...

I'm unable to import correctly using the --compiler option

Having an issue here. I'm trying to bring in the typescript compiler. I used this command: bit import bit.envs/compilers/typescript --compiler Unfortunately, it didn't work. This is the error message: bit import [ids...] import components in ...

Does a typescript module augmentation get exported by default when included in a component library?

Utilizing material-ui and Typescript, I developed a component library. By implementing Typescript module augmentation, I extended the theme options as outlined in their documentation on theme customization with Typescript. // createPalette.d.ts/* eslint-di ...

Is it possible to implement a customized pathway for the functions within an Azure function app?

Recently, I set up a new function app on Azure using Azure Functions Core Tools with Typescript as the language. The app includes a test function named MyTestFunction that responds with an HTTP response when called. This particular function is located in ...

What is the best way to create a React text box that exclusively accepts numeric values or remains empty, and automatically displays the number keypad on mobile devices?

While there are numerous similar questions on StackOverflow, none of them fully address all of my requirements in a single solution. Any assistance would be greatly appreciated. The Issue at Hand Within my React application, I am in need of a text box tha ...

Leveraging Observables in an Angular 2 component to broadcast data to multiple components

Is it possible to utilize Observables in components and which other components can subscribe to them? BugListComponent - The component is injected in the boot.ts file where all services are loaded (where bootstrap is located) import {Subject, BehaviorSub ...

Angular: implementing lazy loading module specifically for development environment (environment.production === false)

I have a lazy loaded module specifically for development purposes and I do not want to include it in the production build. To prevent activation and loading, I have implemented a guard: const routes: Routes = [ { path: 'dev', loadChil ...

Is there a way to inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...

Passing props from pages to components in NextJS: A guide

My nextjs-application has a unique folder structure: components -- layouts --- header.tsx --- index.tsx pages -- index.tsx -- [slug].tsx In the [slug].tsx file, I utilize graphql to fetch data and set the props accordingly: export default ...