How can I use TypeScript in Angular to append two distinct inputs to a list?

I have been working on a form to capture user inputs for name and age, and adding them to a list. However, I am struggling with the implementation in my Typescript file. Can anyone guide me on how to successfully add items to the list?

My HTML and Typescript files are ready with the necessary code. I have set up an onClick function in my Button element, but I need help with what code should be written inside this function to add items to the list.

In the HTML code, I have included the ngRepeat directive, but I am uncertain about how to utilize it in the Typescript file.

Here is a snippet of the HTML code:

<div class="shadow-lg p-5 mb-5 bg-white rounded">
    <ul class = "list-group">
        <li *ngFor="let person of people" class = "list-group-item list-group-item-success">
            {{ person.name }} - {{ person.age }}
        </li>
    </ul>
    <br/>
    <ul class = "list-group">
        <li class = "list-group-item list-group-item-warning">

            <input type="name" class="form-control ng-untouched ng-pristine ng-valid" placeholder="Enter Name" [(ngModel)]="name" ngRepeat="detail in people">   <hr/>

            <input type="number" class="form-control ng-untouched ng-pristine ng-valid" placeholder="Enter Age" [(ngModel)]="age" ngRepeat="detail in people">  <hr/>

            <button type="button" class="btn btn-danger btn-block" (click)="onClick()"> Add </button>
        </li>
    </ul>
</div>

This is a snippet of the Typescript code:

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

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})

export class MenuComponent implements OnInit {

  name: string;
  age: number;

  people: any[] = [{
    "name" : "abdul",
    "age" : 20
  }, {
    "name" : "david",
    "age" : 30
  }, {
    "name" : "ben",
    "age" : 40
  }]

  onClick() {
    this.people.push();
  }

  constructor() { }

  ngOnInit(): void {
  }

}

Answer №1

To update your push method, simply make the following adjustment:

onClick() {
  this.users.push({ name: this.name, age: this.age });
}

For a demonstration, you can check out the example here:

https://example.com/edit/angular-abc123

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

Connect with ionic associates by obtaining their contact number

Here is the code snippet I am working with: import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; import { Screenshot } from '@ionic-native/screenshot'; import { AlertController, ...

Guide on parsing logs containing JSON objects utilizing Fluentd

In my nginx log file, I come across lines like this: 127.0.0.1 192.168.0.1 - [28/Feb/2013:12:00:00 +0900] "GET / HTTP/1.1" 200 777 "-" "Opera/12.0" - <{"key1":"value1","key2":98765,"key3":false,"key4":["one","two"],"key5":{"key22":98765,"key23":false,"k ...

Adding numerous elements at specific locations

Does anyone know how to insert multiple elements into specific positions in a document? For example, I want to always place ItemA1 in the first position and Item A2 in the second position, and so on. The issue I'm facing is that the method parent.inse ...

Building with bricks and mortar does not involve organizing visual content

I'm currently trying to organize some fairly large images using masonry, but the code below doesn't seem to be working. I'm using node.js with express and have installed the masonryjs package in an attempt to make it work, but that approach ...

What is the best way to elegantly extract a subset array from an array of objects?

Imagine you have the following array of objects: var myObject = [ {A:1, B:2, C:3}, {A:4, B:5, C:6}, {A:7, B:8, C:9}, ] How would you efficiently retrieve a subset with the Y values from this array? var subset = [ B:2, B:5, B:8 ] ...

Safari 11.1 and Angular 9 - config object missing a defined key-value

While using Safari, I have encountered a problem in the Primeng input text field. When I type into the text box, errors are logged into the console. handleKeypress — injected.entry.js:8231TypeError: undefined is not an object (evaluating 'settin ...

Node.js Multer encountering undefined req.file issue when handling multiple file uploads

FIXED: ( NO req.file ) ( YES req.files ) My project requires the ability to upload multiple files. If single image uploads are working but multiple image uploads aren't (uploading to files), I need req.file.filename in order to write the image path ...

"Create a new controller with Angular using the constructor method

Looking to consolidate common functionality in my controllers, I want to utilize inheritance in a parent controller instead of creating a service. Most examples utilizing the $injector.invoke function require the parent's constructor function to be a ...

Utilizing a React npm component within an Angular project: A step-by-step guide

After successfully creating a simple react component and publishing it to the NPM registry, I encountered an issue when trying to use the same plugin in an Angular project. The custom plugin can be found at: https://www.npmjs.com/package/reactcustomplugin ...

Decoding intricate JSON data into a Java object (List) using Jackson

As a newcomer to Json, I am facing the challenge of deserializing a complex Json that contains complex types (such as entete, pied-depage, corps (List), nomain, labels, lieu, garantie, Elt), all of which are classes from my program. My goal is to deseriali ...

The functionality of JSON.stringify does not take into account object properties

Check out the example on jsfiddle at http://jsfiddle.net/frigon/H6ssq/ I have encountered an issue where JSON.stringify is ignoring certain fields. Is there a way to make JSON.stringify include them in the parsing? In the provided jsfiddle code... <s ...

Node.js route leads to a 404 error page due to a simple configuration

Trying to set up two separate routes using NodeJS with the express framework and Angular on the client side. The index page successfully renders at localhost:3000/. However, when attempting to render the login page by visiting localhost:3000/login, a GET / ...

Transform a List of dynamic elements into a List of Strings

Fetching information from the server indicates that it is of type List, as shown by the runtimeType. Currently, I am utilizing cast<String>() to retrieve List<String>. Is this the only correct method? var value = await http.get('http://12 ...

Error: dispatch function does not exist - TypeMismatch

Recently, I started working with react-redux and incorporated the react-thunk middleware into my project. However, I encountered an issue where I kept receiving the error "Uncaught TypeError: dispatch is not a function" whenever I attempted to execute my a ...

"Trouble with Angular's http.get method failing to retrieve data from MySQL through Node

I am struggling to retrieve data from MySQL using Angular and Node.js. Despite trying, I am unable to make it work. When I check Postman using the link http://localhost:8080/locations, I can see the data. { "status": "200", "items": [ { "cit ...

Communicating Data Between Brother Components in Angular 10

I'm looking for a way to exchange data between two sibling components effectively. Component 1: Component 1 serves as my navigation bar and includes an option to change the language of the app (using ngx-translate). This language selection is present ...

Creating a versatile Angular component with personalized settings without relying on the @Input directive

Hello fellow members of the Angular community, I am seeking advice on how to create a generic icon component that avoids code duplication. custom-icon-component: @Component({ selector: 'app-custom-icon', template: ` <style> ...

Parsing of the module failed due to an unexpected character appearing when trying to insert a TTF file into the stylesheet

As a newcomer to Angular, I recently completed the tutorial and am now working on my first app. While trying to add an OTF file, everything went smoothly. However, when I made a change to my app.component.css file and included this code snippet: @font-fa ...

Tips for setting up a jQuery auto-suggest feature that fetches both the value and ID

Looking for a solution similar to an auto-complete feature, where a user can select from options already in a database or add new entries if not found. The goal is to retrieve the ID, send it to PHP, and check if it already exists. If not, a new entry shou ...

ngf-select fails to activate

Having Trouble with AngularJS 1.6.9 File Upload I'm facing an issue with a simple file upload on JSFiddle using AngularJS 1.6.9. The ngf-select event doesn't seem to be triggering even though everything else appears to be working fine, and there ...