Issue with callback and logic in Angular 2.0 form handling

As a beginner in Angular, I am attempting to develop a simple script that updates the price when the value of a form input changes. There are various methods for utilizing Angular with class-driven and directive-driven models. Despite reading the documentation on the main Angular website, I have not been successful.

import { Component } from '@angular/core';
export class Ticket {
  ticketNumber: number;
  name: string;
  price: number;
}
@Component({
  selector: 'my-app',
  template: `
    <form name="myForm">
    <div class="ticket box_shadows">
       <div class="ticket_title">{{ticket.name}}</div>
        <input type="number" name="myInput" class="ticket_amount" min="1" max="10" value="{{ticket.ticketNumber}}" required ng-class="updatePrice(price,ticketNumber)">
        <div class="ticket_details"><input class="ticket_details_input" type="text"  placeholder="Name:" required></div>
        <div class="ticket_details"><input class="ticket_details_input" type="email" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82fbedf7f0c2e7efe3ebeeace1edef">[email protected]</a>" required></div>
        <div class="ticket_details"><input class="ticket_details_input" type="text"  placeholder="+852" required></div>
        <div class="ticket_price">$ <input type="number" name="price" value="{{ticket.price}}|>
        <button type="button" class="ticket_button">Book</button>
        </div>
    </div>
    </form>
    `
})
//creates the class
export class AppComponent {
  ticket: Ticket = {
    ticketNumber: 1,
    name: 'Ticket',
    price: 300 
  };
  //updates the price on a new click
  updatePrice(value, ticketN){
      value = value * ticketN;
      return value; 
      // this then needs to be passed back to the price input field. 
  }
}

----- UPDATE ------- Having trouble calling two classes and making them interact, I decided to strip out the code and start fresh. Here is what I used to make it function properly.

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

@Component({
  selector: 'my-app',
  template: `
    <form>
    <div class="ticket box_shadows">
        <div class="ticket_top">
            <div class="ticket_title">{{title}}</div>
          <input type="number" name="myInput" class="ticket_amount" min="1" max="10" [(ngModel)]="ticket" (click)="updatePrice()" required>
        </div>
        <div class="ticket_btm">
            <div class="ticket_price"><span>$</span><input type="number" [(ngModel)]="totalPrice" class="ticket_price_number" disabled></div>
            <div class="ticket_btm_spacer"></div>
            <button type="button" class="ticket_button">Book</button>
        </div>
    </div>
    </form>
    `
})
export class AppComponent {
  ticket: number = 1;
  title: string = "Ticket";
  price: number = 300;
  totalPrice: number = 300; 
  updatePrice(){
    this.totalPrice = this.price * this.ticket;
    if(this.ticket >= 2){
      this.title = "Tickets";
    }
    else{ this.title = "Ticket";}
  } 
}

Answer №1

Implementing a two-way binding for input values requires the use of ngModel.

<input [(ngModel)]="ticket.price">

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

ExpressJS receives mysterious object communication from AngularJS controller

Currently, I am working on a project that involves creating a login page for an admin that redirects to a dashboard. The server-side is built using Express.js, while the client-side utilizes AngularJS. The AngularJS controller below is used to retrieve da ...

What is the method to track the movement of the mouse in the reverse direction?

I am looking to create a unique div that moves in the opposite direction of the mouse cursor within another div called .box. As the mouse moves, I want the red box to create a subtle parallax effect by slightly moving in the opposite direction. Instead of ...

Retrieve an object using a variable

Essentially, my question is how to extract a value from a variable and input it into a sequence. Being Dutch, I struggle to articulate this query correctly. var channelname = msg.channel.name; "description": `${config.ticketlist.channelname.ticketmessage} ...

What could be causing this minimal Angular - WebTorrent configuration to fail?

The setup appears to be quite straightforward. Check out the Webtorrent usage reference here This is how I have my setup: import WebTorrent from 'webtorrent'; @Component({ selector: 'app-root', standalone: true, template: `bla` ...

Using MIPS Assembly Language: Displaying Register Content on Screen

I'm working on replicating a simple form of debugging in MIPS similar to javascript. I am wondering how I can achieve the equivalent of this ($t0 represents a javascript variable here): console.log($t0); In simpler terms, I am looking for the metho ...

What is the best way to retrieve a value from one array based on its index in React Native?

Looking to populate the centreValues array with values from another array const centreValues=[ { title:'Type', value:centreDetail.location_type }, { title:'Address', value:centreDetail.address1+centreDetail.ad ...

Loading data into a database using JSON format with JavaScript

I need to extract data from a JSON String stored in a JavaScript variable and use it to generate an SQL script. How can I loop through the JSON string to produce an output like the following? INSERT INTO table VALUES ('$var1', '$var2', ...

Obtain the image and store it in the designated storage location

I need help with a web page that features a profile viewing section. I have an empty image placeholder and when clicked, it prompts the user to browse for an image. However, I am struggling with saving the selected image into storage. Below is my code snip ...

A guide on iterating through a multi-dimensional array in Javascript and organizing the results in a specified sequence

Updated on 18th January, 2021 (refer to bold changes) I'm currently facing difficulties while attempting to iterate through a nested array and then organize the output in a specific order. Can you assist me in finding a solution to make this work or ...

What is the best way to send multiple arrays of JSON objects to a Stimulsoft report using JavaScript?

I am currently working with this JavaScript code snippet: var viewer = new window.Stimulsoft.Viewer.StiViewer( null, "StiViewer", false ); var report = new window.Stimulsoft.Report.StiReport(); const { data: reportData } = await GetRequest ...

Unexpected TypeError occurred when trying to Fetch data from an Express Server hosted on Window object

Error Message : Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name Feeling stuck as I looked around, unsure of what's causing this issue. My goal is to develop a website that can eventually make a ...

The value in the span and input will be identical, with the span only updating when the form is submitted, not in real-time with AngularJS

I am attempting to create a form where the variable in the span remains unchanged, but the value in the form stays the same. <b>Example</b> https://codepen.io/Turqus/pen/WXGzyp I am looking for a way to ensure that the variable in the span i ...

What is the concept of nested includes in sequelize?

Is it possible to perform a nested include in Sequelize? I have a table called products that has a one-to-many relationship with comments, and the comments table has a many-to-one relationship with the users table. Each comment has a user_id and product_id ...

Finding the parent directory path within gulp.dest(): A step-by-step guide

I've recently started using Gulp and I'm facing an issue when trying to output my files to their parent directory. This is how my directories are structured: app/page_a/less/a.less app/page_a/css My desired outcome is: app/page_a/less/a.less ...

Setting up Webpack for react-pdf in a Next.js application

In my Next.js application, I am utilizing the react-pdf library to generate and handle PDF files on the client side without involving the server. However, I am facing challenges in setting up Webpack for Next.js as I lack sufficient expertise in this area. ...

Obtaining static images from the public directory with getStaticProps in Next.js

Next.js provides a thorough method for accessing images from the /public/ folder, where static assets are stored. This involves using Node's fs module and fetching them within the getStaticProps function. Here is an example: export async function get ...

In angular, concealing the pagination bar can be achieved when the quantity of pages is lower than the items per page count. Let's delve into

I am facing an issue where I need to hide the pagination bar if the number of pages being rendered is less than the items per page. I attempted to use ng-show but it was not successful. <tr ng-repeat="row in allItems"> ...

What is the best way to assign default values when destructuring interfaces within interfaces in TypeScript?

My goal here is to create a function that can be used with or without arguments. If arguments are provided, it should work with those values; if not, default values should be used. The issue I'm facing is that although there are no TypeScript errors ...

What is the best way to display my images within Material UI Cards using React with Typescript?

I'm currently faced with a challenge of rendering images within Material UI's cards. I am successfully passing props to each card from a constants.tsx file where the heading, description, and bodyHeader are all properly read, but for some reason, ...

The Battle: AJAX FormData vs encodeURI

When utilizing jQuery's encodeURI(), the data transmitted through AJAX appears in this format: key1=true & key2=34 & ... In order to send an image via AJAX, I employ the FormData() method, resulting in the AJAX data without an image looking ...