Creating a new item in Angular 2 using user input

Just dipping my toes into Angular2 and attempting to append a new item to the list through input. However, upon clicking submit, instead of text I get [object Object].

Check out the code snippet below:

app.component.html

<form (submit)="addItem(item)">
    <md-input-container>
      <input [(ngModel)]="name" mdInput placeholder="add" name="addNew">
    </md-input-container>
      <button type="submit" md-icon-button>
          <i class="material-icons">send</i>
    </button>
    </form>

app.component.ts

items = Players;
 name;

 addItem(name): void {
        this.items.push(new Player({
            name : name
        }));
    }

player.ts

export class Player {
    id: number;
    name: string;
    count: number;

    constructor(name){
        this.id;
        this.name = name;
        this.count = 0;
    }

all-players.ts

export let Players: Player[] = [
];

Appreciate any help or suggestions provided!

Answer №1

I am going to provide a detailed solution.

Within your component (TS file) :

items = Players;
name;

addItem() { this.items.push(new Player({ name : this.name })); }

In your HTML :

<form (submit)="addItem()" novalidate>
    <md-input-container>
        <input [(ngModel)]="name" mdInput placeholder="add" name="addNew">
    </md-input-container>
    <button type="submit" md-icon-button>
        <i class="material-icons">send</i>
    </button>
</form>

It seems likely that the form is being submitted twice.

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

Revising HTML content when Angular array is modified

I have a code snippet below where I am updating the value of an object in the first item of an array. However, I'm struggling to find a way to "refresh" the HTML view so that the changes are immediately reflected on the browser. var dataArr ...

What steps should I take to resolve the 'buffer' issue in my jsonwebtoken?

As I am still new to ReactJS and the MERN stack in general, the code in Activate.js below essentially means that when the useEffect() hook is triggered, we will receive the jwt token extracted from the route parameter/url using the {match} props. This toke ...

Transforming an ES6 JSON object into a dictionary: a step-by-step guide

As someone who is new to learning ES6 and JQuery, please forgive me if this question has been asked before (I couldn't find similar ones). Currently, I am working on retrieving data from a JSON file in the following format: { EUR: { code: "EUR" ...

Transferring the Header component from standard React to Gatsby: Eliminating Duplicates

After initially creating a front-end using create-react-app, I decided to transfer it to Gatsby.js. However, I encountered an issue where the component Header.js was being displayed multiple times. Can anyone explain why this would happen? https://i.sstat ...

Encountered an issue while trying to extract data from state - property of null cannot

I'm facing an issue trying to show a navigation item only when a specific flag is true. The problem arises when I attempt to extract data from it, as it returns undefined. Below is the code snippet I have created for this scenario: let navigate = useN ...

Change the className of an element in React upon clicking it

I just finished developing a menu bar using ReactJS with some basic routing features. Here is the JSX code for the component: class TopBar extends Component { state = { menus: [{id:0,menu:"Home"}, {id:1,menu:"Contact"}, {id:2,menu:"About"}] } a ...

I am looking to showcase the information from two separate collections

I am looking to display data from two separate mongoose collections. I have a Member collection and a Property collection. Below is my code for fetching the data: const Property = require('../models/propsSchema') const Members = require(&apo ...

Maintain the value of `this` using a recursive setImmediate() function

Hey there! I'm working on a node.js app where I need to utilize setImmediate() to recursively call a function while maintaining its context for the next iteration. Let's take a look at an example: var i=3; function myFunc(){ console.log(i ...

Why does the pound symbol in z-index always show up in Angular?

Having an issue with my code where I set a z-index in the CSS like this: .mat-mini-fab { position: absolute; right: 5px; top: 4px; z-index: 999; box-shadow: none !important; } However, whenever I visit my site, the z-index is not being appl ...

Utilizing Observables in NestJS: Exploring SSE and EventEmitter

I am working on a project where I need to display an event that occurs in the backend on the frontend. Since it is a one-way communication, I have decided to use SSE (Server Sent Events) in nestjs to push the event to the frontend. The setup, as per the do ...

Differentiating Service Class and Typescript Class in Angular 6

I am looking for a detailed explanation of service classes in Angular. From my perspective, both service classes and typescript classes serve the same purpose. So, what sets them apart from each other? ...

What steps can I take to prevent ng-bootstrap modal from automatically centering the content within the modal?

Looking for a solution to a UX issue with my Angular ng-bootstrap modal. The problem arises when displaying messages of varying lengths - if the message is longer than the screen's vertical resolution, it gets centered on the screen. This causes incon ...

Electron Developer: "An issue has occurred within the primary process - Callback function missing"

My Electron application runs smoothly when launched from the command line with npm start. However, I am now looking to distribute the application as user-friendly installers for Mac/Windows/Linux. To achieve this, I am utilizing Electron-Builder for packag ...

Switch up the perspective/component without altering the URL

I have implemented a 404 error page functionality successfully using VueRouter: const router = new VueRouter({ routes: [ // ... { path: '*', component: NotFound, name: '404', ...

Guide to make a loading animation button through the use of HTML, CSS, and JavaScript

"Hello, I am currently in the process of working on a project and am interested in implementing a button with a loading animation that can be displayed during actions like form submission or content loading. I'm seeking some advice or code sample ...

Overriding filters in AngularJS and injecting dependencies into modules

My application relies on two filter modules: var app = angular.module('MyApp',['Filter1','Filter2']); Both modules contain filters with the same name: var filterapp1 = angular.module('Filter1',[]); filterapp1.f ...

Improved Separation and Design in Node.js Application

I have developed a node application using express. I am trying to organize the different layers to enable unit testing of the application... However, I am facing an issue on how to call the router.js file that handles the post/get/delete methods in the ap ...

Creating a spinning or swinging motion using scriptaculous shake

I want to create a unique hover effect where the item doesn't shake from side to side, but instead smoothly slides like a clock pendulum moving from 180-90 degrees. I'm not certain about the exact numbers right now. Is this achievable with Script ...

Utilizing Vue's v-for directive to display computed properties once they have been fully loaded

Utilizing the v-for directive to loop through a computed property, which is dependent on a data attribute initialized as null. I'm planning to load it during the beforeMount lifecycle hook. Here's a simplified version of the code: <th v-for= ...

Is it wrong to use <match v-for='match in matches' v-bind:match='match'></match>? Am I allowed to incorporate the match variable from the v-for loop into the v-bind attribute on the

I am attempting to display HTML for each individual match within the matches array. However, I am uncertain if <match v-for='match in matches' v-bind:match='match'></match> is the correct syntax to achieve this. To clarify, ...