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 is the best method for retrieving information from a Java REST API using Angular 7?

view image descriptionaccess this API link here Can someone explain the process of retrieving data from this api? ...

Is SASS stylesheet supported by the Angular 2 Ahead-of-Time compiler?

Considering giving Angular 2 Ahead-of-Time compilation another shot. I'll have to do some significant refactoring since my current custom build process will need to be reworked. Prior to diving in, I'm curious: if I reference external .scss fil ...

Is there a way to run a node script from any location in the command line similar to how Angular's "

Currently, I am developing a node module that performs certain functions. I want to create a command similar to Angular's ng command. However, I am facing compatibility issues with Windows and Linux operating systems. Despite my attempts to modify the ...

What is the best way to activate a submit button when at least one checkbox is selected?

I checked out Mark's solution on Stack Overflow regarding disabling a button if no checkboxes are selected in Angular2. However, I have more than one array to consider. How can I adjust the code provided in the link for my situation? Alternatively, d ...

Adjusting the focal point of a brochure on open street map

I am currently working on initializing a map in an Angular application using leaflet with openstreetmaps. I have set the center of the map so that it is displayed to the user when they open the site. However, I am now trying to figure out how to dynamica ...

Error encountered when attempting to retrieve token from firebase for messaging

I am currently working on implementing web push notifications using Firebase. Unfortunately, when attempting to access messaging.getToken(), I encounter an error stating "messaging is undefined." Below is the code snippet I am utilizing: private messaging ...

Creating an enum from an associative array for restructuring conditions

Hey everyone, I have a situation where my current condition is working fine, but now I need to convert it into an enum. Unfortunately, the enum doesn't seem to work with my existing condition as mentioned by the team lead. Currently, my condition loo ...

Streamlining the deployment process of Angular applications on IIS through automation tools such as Docker and Jenkins

I am currently manually deploying my Angular application on an IIS server by copying the build from my system to a specific location on the server. The code for my application is stored in a TFS repository. My application's backend is powered by Mul ...

Utilizing autocomplete feature for Google Maps API search within Ionic 3

Currently, I am exploring the world of Google APIs and attempting to incorporate the Google Maps plugin into Ionic3. My main goal is to retrieve the geocordinates of any location entered by a user in the search bar. This requires integrating the autocomple ...

Combining information from two different sources to create a more comprehensive dataset

Two get requests are returning the following data: [{ id: 1, hId: 2 }, { id: 6, hId: 1 }] The second request returns: [{ id: 1, name: 'Bob' }, { id: 2, name: 'Billy' }, { id: 6, name: 'John' }] The object ...

The innerHTML inside Angular components appears scrambled, with only the final innerHTML rendering correctly

When working on my Angular project (version 8), I encountered an issue where a list of static HTML content retrieved from a database is not rendering correctly in the parent HTML. Strangely, only the last div with innerHTML is being rendered correctly, whi ...

Sorting Angular data using database queries

I'm currently setting up a blog for my website. Everything is running smoothly with the database, but I've run into an issue with the order of my posts - they are displayed in the opposite order that I want. The oldest post is showing at the top, ...

Tips for creating a test to choose a movie from the MuiAutocomplete-root interface

I am currently utilizing Material UI with React using Typescript and I am looking to create a test for the autocomplete functionality using Cypress. Here is the approach I have taken: Identifying the Autocomplete component and opening it, Choosing an opti ...

Unlocking the Secrets of Passing ID Parameters Between Pages and Fetching Data from External APIs in Ionic 4

Before I get into it, apologies for the basic question, but I'm struggling to figure this out. Here's my issue: I have a list of categories that are being fetched from a nodeJS api. My goal is to fetch the subcategories based on the id from the d ...

Utilizing an object's value as a key for a separate object

Here's an overview of my current object structure: import { imageOne, imageTwo } from "./images"; export const imageKeyMap = { "one": imageOne, "two": imageTwo } The definitions for imageOne and imageTwo ...

What is the most efficient method for validating an exception in Protractor?

In recent code reviews within our team, a discussion arose about writing tests that assert on expected exceptions. While this is correct, the method used involved a try/catch block, which some believe may not be the most performant approach. This raises th ...

How to modify the port for the inspector in ng serve configuration?

Whenever I try to run ng serve server in the command line, it fails with the following message: Starting inspector on localhost:7777 failed: address already in use It is expected since there is already another instance running. So, how can I change the ...

Creating a React component with a column allowing multiple checkbox selections in NextUI table

Setting up multiple "checkbox" columns in a table using the NextUI table has been my current challenge. Each row should have selectable checkboxes, and I want these selections to be remembered when navigating between pages, running searches, or removing co ...

Error message in TypeScript: A dynamic property name must be a valid type such as 'string', 'number', 'symbol', or 'any'

Attempting to utilize the computer property name feature in my TypeScript code: import {camelCase} from "lodash"; const camelizeKeys = (obj:any):any => { if (Array.isArray(obj)) { return obj.map(v => camelizeKeys(v)); } else if (ob ...

Error message 'Module not found' occurring while utilizing dynamic import

After removing CRA and setting up webpack/babel manually, I've encountered issues with dynamic imports. The following code snippet works: import("./" + "CloudIcon" + ".svg") .then(file => { console.log(file); }) However, this snip ...