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";}
}
}